不要再搜啦,满足你的需要,封装保留小数点后两位

function keepNum(num) {
var result = parseFloat(num),
result = Math.round(num * 100) / 100;
var s_x = result.toString();
var pos_decimal = s_x.indexOf('.'); // -1 代表有小数点
console.log(result,s_x,pos_decimal)
if (pos_decimal < 0) {
pos_decimal = s_x.length; //result 转化的整数又toString()需要加.
s_x += '.';
}
while (s_x.length <= pos_decimal + 2) {
s_x += '0'; // 如果只有一位小数,进行补位
}
return parseFloat(s_x); // 最后又转化成了浮点型便于加减操作
}

效果如下: 10.56666

10.57

猜你喜欢

转载自www.cnblogs.com/panax/p/9389605.html