js 保留2位小数

一、四舍五入法

1.jquery 小数计算保持精度,同时保留两位数

toFixed() 方法可把 Number 四舍五入为指定小数位数的数字。

var num = 1.45698;
num = parseFloat(num.tofixed(2));

注意toFixed方法返回的结果是字符串类型

2.toFixed 四舍五入遇到坑。

1.235.toFixed(2) = 1.23
1.2350001.toFixed(2) = 1.24

3.

//四舍五入法
Number.prototype.toRound = function (num) {
return Math.round(this * Math.pow(10, num)) / Math.pow(10, num);
};

Math.round()执行标准舍入,即它总是将数值四舍五入为最接近的整数。

pow() 方法可返回 x 的 y 次幂的值。

document.write(Math.pow(1,10) + "<br />")   //1
document.write(Math.pow(2,3) + "<br />")    //8

round() 方法可把一个数字舍入为最接近的整数。返回与 x 最接近的整数。进行四舍五入 

document.write(Math.round(0.50) + "<br />")   //1
document.write(Math.round(0.49) + "<br />")   //0
document.write(Math.round(-4.40) + "<br />" )   //-4

二、进一法

Number.prototype.toCeil = function (num) {
return Math.ceil(this * Math.pow(10, num)) / Math.pow(10, num);
};

Math.ceil()执行向上舍入,即它总是将数值向上舍入为最接近的整数;将小数部分一律向整数部分进位

三、去尾法

Number.prototype.toFloor = function (num) {
return Math.floor(this * Math.pow(10, num)) / Math.pow(10, num);
};

Math.floor()执行向下舍入,即它总是将数值向下舍入为最接近的整数;一律舍去,仅保留整数

原文地址:https://www.cnblogs.com/kangby/p/8269356.html