js保留四位小数
作者:互联网
超过4位截取保留4位,不足4位保留原位数不补0
//保留4位小数
var number = 12.3321432;
number = String(number).replace(/^(.*\..{4}).*$/,"$1");
number = Number(number); // number = 12.3321
//保留2位小数
var reg = /^(.*\..{2}).*$/;
var number2 = 12.3;
number2 = String(number2).replace(reg ,"$1");
number2 = Number(number2); // number2 = 12.3 不足保留位数不补0
超过4位截取保留4位,不足4位补足0
getFloat = function(number, n) {
n = n ? parseInt(n) : 0;
if(n <= 0) {
return Math.round(number);
}
number = Math.round(number * Math.pow(10, n)) / Math.pow(10, n); //四舍五入
number = Number(number).toFixed(n); //补足位数
return number;
};
console.log(getFloat('0', 4)); //0.0000
console.log(getFloat('2.08', 4)); //2.0800
console.log(getFloat('2.08500', 4)); //2.0850
console.log(getFloat('2.08996', 4)); //2.0900
console.log(getFloat('2.08994', 4)); //2.0899
toFixed()方法
var a =123.456789;
alert(a.toFixed(4));// 四舍五入保留四位小数
需注意,保留两位小数,将数值类型的数据改变成了字符串类型
Math.floor()向下取整
let numBoolean = Math.floor((this.editFormData.amount / this.thresholdYuan) * 10000) / 10000 >= 0.005
标签:getFloat,console,log,number,js,number2,四位,Math,小数 来源: https://blog.csdn.net/weixin_49075393/article/details/121750723