Home > Web Front-end > JS Tutorial > body text

How to round js values

一个新手
Release: 2017-09-08 13:23:34
Original
2731 people have browsed it

1.toFixed() method can round Number to a number with specified decimal places.

NumberObject.toFixed(num)
Copy after login

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会出错,这东西好像只能传一个数字进去,字符串会爆不是一个方法
Copy after login

Bug in the method:

Number(13.35).toFixed(1); //13.3 
Number(0.055).toFixed(1); //0.1
原因:原生toFixed(x)截取小数的时候会有误差
//如果要修改这个缺陷,可以把js中的number类型的tofixed方法重写。
Copy after login

2.Math.round() Method rounds a number to the nearest integer.

Math.round(x)
Copy after login

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,小数点后位数不对!)
Copy after login
原因:当num是字符串,进行乘法操作时,进行了类型转换,后缀零被丢弃了,导致位数不足,这个时候我们就应该进行补0
Copy after login

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"
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!