Home  >  Article  >  Web Front-end  >  Summary of rounding methods in javascript_javascript skills

Summary of rounding methods in javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:26:221347browse

The rounding function toFixed(n) in native javascript, n is the number of decimal places to be retained. (0<= n <=20)

Copy code The code is as follows:

var num=1.0999;
console.log(num.toFixed(20));

http://jsfiddle.net/14x0vhu6/

The output value is not the expected 1.0999, but 1.09990000000000009983. This needs attention, and the reason needs to be improved.

In addition, in different browser versions, if the decimal point and the previous digit to be intercepted are both 0, interception may not follow common sense.

Copy code The code is as follows:

var num=0.07;
console.log(num.toFixed(1));

http://jsfiddle.net/ogwnw2j3/
Value may be 0.0

The method of processing is to add 1 before using the toFixed method, and then subtract 1 after using it.

Copy code The code is as follows:

var number=0.07
var fixNum = new Number(number 1).toFixed(1);//Add 1 before rounding
var fixedNum = new Number(fixNum - 1).toFixed(1);//After rounding, subtract 1, then round again
console.log(fixedNum);

http://jsfiddle.net/euvn0L1g/

Statement:
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