javascript rounds the method summary

  • 2020-05-05 10:56:38
  • OfStack

The rounded function toFixed(n) in native javascript, n being the decimal number to be reserved. (0 < = n <

= 20)


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

http://jsfiddle.net/14x0vhu6/

The output value is not expected to be 1.0999, but   1.09990000000000009983. This should be noted, but the reasons for this need to be improved.

In addition, in different versions of the browser, if the decimal point before and to intercept the first bit is zero, may appear in the case of arbitrary interception.


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

http://jsfiddle.net/ogwnw2j3/
The value may be 0.0
 
The way to do this is to add 1 to the toFixed method and then subtract 1 from it.


var number=0.07
var fixNum = new Number(number + 1).toFixed(1);// Add before rounding 1 
var fixedNum = new Number(fixNum - 1).toFixed(1);// I'll round it and subtract 1 I'll round it again  
console.log(fixedNum);

http://jsfiddle.net/euvn0L1g/


Related articles: