方法一:使用toFixed保留两位小数
var num1 = 55.3715;
console.log(num1.toFixed(2));
打开浏览器调试工具,可以看到如下打印结果,55.37保留了两位小数,之后的两位舍弃

toFixed自带四舍五入的功能
var num2 = 55.3755;
console.log(num2.toFixed(2));
var num3 = 55.3745;
console.log(num3.toFixed(2));
看下面打印结果,小数第三位为5时,或大于5时进一位,小于5后面几位直接舍弃

toFixed自带补位功能
var num4 = 55.3;
console.log(num4.toFixed(2));
var num5 = 55;
console.log(num5.toFixed(2));
从打印结果可以看出,55.3补一位0,55补了两位00

方法二:substr直接按字符串截取
var num1 = 55.3785 + "";
console.log("substr方式保留两位小数:");
console.log(num1.substr(0,num1.indexOf(".")+3));
这种方式没有四舍五入的功能,直接按位截取的,也没有补位功能

方法三:浮点数四舍五入
var num1 = parseFloat(55.7856);
if (!isNaN(num1)) {
num1 = Math.round(num1*100)/100;
console.log("将浮点数四舍五入,取小数点后2位:");
console.log(num1);
}

上面的方法有四舍五入的功能,但没有补位的功能,可以通过以下方式实现
var num1 = parseFloat(55);
if (!isNaN(num1)) {
num1 = Math.round(num1*100)/100;
var str = num1.toString();
var rs = str.indexOf('.');
if (rs < 0) {
rs = str.length;
str += '.';
}
while (str.length <= rs + 2) {
str += '0';
}
console.log("将浮点数四舍五入,取小数点后2位,位数不够进行补位:");
console.log(str);
}

7
以上就是js保留小数的几种方法,可以根据自己的需要选择
END