0
点赞
收藏
分享

微信扫一扫

js中保留两位小数, js中使用forEach遍历数组

js中保留两位小数

1、四舍五入

var num =354.15687441568;
num = num.toFixed(2); // 输出结果为 354.16

2、不四舍五入

第一种,先把小数边整数:

Math.floor(89.1564835421 * 100) / 100 ``// 输出结果为 89.15

第二种,当作字符串,使用正则匹配:

Number(89.1564835421.toString().match(/^\d+(?:\.\d{0,2})?/)) ``// 输出结果为 89.15,不能用于整数如 10 必须写为10.0000

3、其他方式

//四舍五入保留2位小数(若第二位小数为0,则保留一位小数)
function keepTwoDecimal(num) {
 var result = parseFloat(num);
 if (isNaN(result)) {
 alert('传递参数错误,请检查!');
 return false;
 }
 result = Math.round(num * 100) / 100;
 return result;
}
//四舍五入保留2位小数(不够位数,则用0替补)
function keepTwoDecimalFull(num) {
 var result = parseFloat(num);
 if (isNaN(result)) {
 alert('传递参数错误,请检查!');
 return false;
 }
 result = Math.round(num * 100) / 100;
 var s_x = result.toString();
 var pos_decimal = s_x.indexOf('.');
 if (pos_decimal < 0) {
 pos_decimal = s_x.length;
 s_x += '.';
 }
 while (s_x.length <= pos_decimal + 2) {
 s_x += '0';
 }
 return s_x;
}

js中使用forEach遍历数组

this.dataList = response.data.data.records;
this.dataList.forEach(function (element) {
    element.arr = (element.arr / 1024).toFixed(2);
});

参考地址: https://blog.csdn.net/firstcode666/article/details/121568899 https://jingyan.baidu.com/article/fc07f98940143812ffe51939.html https://www.jb51.net/article/134067.htm

举报

相关推荐

0 条评论