1.toFixed() method can round Number to a number with specified decimal places.
NumberObject.toFixed(num)
num must be written, specifying the number of decimal places, which is a value between 0 ~ 20, including 0 and 20. Some implementations can support a larger range of values. If this parameter is omitted, 0 will be used instead.
当num超过20的时候,js会出错,这东西好像只能传一个数字进去,字符串会爆不是一个方法
Bug in the method:
Number(13.35).toFixed(1); //13.3
Number(0.055).toFixed(1); //0.1
原因:原生toFixed(x)截取小数的时候会有误差
//如果要修改这个缺陷,可以把js中的number类型的tofixed方法重写。
2.Math.round() Method rounds a number to the nearest integer.
Math.round(x)
x is the value to be calculated. This method returns the nearest integer to the given numeric expression.
Existing bug
##
Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2); //num是待处理数字Math.pow(10, 2)=100
当num = 10.10500时,计算上述表达式可得10.11。(正常)
当num = "10.50000"时(注意这里是字符串),计算上述表达式可得10.5。(damn it,小数点后位数不对!)
原因:当num是字符串,进行乘法操作时,进行了类型转换,后缀零被丢弃了,导致位数不足,这个时候我们就应该进行补0
Solution:
var iTofixed =function(num,fractionDigits) {
return (Math.round(num*Math.pow(10,fractionDigits))/Math.pow(10,fractionDigits)+Math.pow(10,-(fractionDigits+1))).toString().slice(0, -1)
};
iTofixed('13.5000',3);
//"13.500"
The above is the detailed content of How to round js values. For more information, please follow other related articles on the PHP Chinese website!