Home > Web Front-end > JS Tutorial > How to round js values

How to round js values

一个新手
Release: 2017-09-08 13:23:34
Original
2941 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:

<span style="color:#33cc00">Number(13.35).toFixed(1); //13.3 <br>Number(0.055).toFixed(1); //0.1<br>原因:<span style="font-size:13.3333px; font-family:PingFangSC-Regular,Verdana,Arial,微软雅黑,宋体">原生toFixed(x)截取小数的时候会有误差</span><br>//如果要修改这个缺陷,可以把js中的number类型的tofixed方法重写。</span>
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

##

<span style="background-color:rgb(255,255,255)"><span style="color:#009900">Math.round(num * Math.pow(10, 2)) / Math.pow(10, 2);  //num是待处理数字</span></span><span style="color:rgb(0,153,0); font-size:13.3333px; font-family:PingFangSC-Regular,Verdana,Arial,微软雅黑,宋体; background-color:rgb(255,255,255)">Math.pow(10, 2)=100</span><span style="background-color:rgb(255,255,255)"><span style="color:#009900"><br>当num = 10.10500时,计算上述表达式可得10.11。(正常)<br>当num = "10.50000"时(注意这里是字符串),计算上述表达式可得10.5。(damn it,小数点后位数不对!)</span></span>
Copy after login
原因:当num是字符串,进行乘法操作时,进行了类型转换,后缀零被丢弃了,导致位数不足,这个时候我们就应该进行补0
Copy after login

Solution:

<span style="background-color:rgb(255,255,255)"><span style="color:#003300">var iTofixed =function(num,fractionDigits) {<br> return (Math.round(num*Math.pow(10,fractionDigits))/Math.pow(10,fractionDigits)+Math.pow(10,-(fractionDigits+1))).toString().slice(0, -1)<br>};<br>iTofixed('13.5000',3);<br>//"13.500"</span></span>
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