This article mainly introduces the summary of javascript rounding methods and provides related examples. For more information, see The rounding function toFixed (n) in the native javascript ), n is the number of decimal places to be retained. (0 <= n <= 20)
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. you need to pay attention to this. The reasons are to be improved.
In addition, in different browser versions, if the first digit before the decimal point and the first digit to be truncated are both 0, it may be unreasonable to intercept.
The code is as follows:
Var num = 0.07;
Console. log (num. toFixed (1 ));
Http://jsfiddle.net/ogwnw2j3/
The value may be 0.0
The solution is to add 1 before using the toFixed method, and then subtract 1 after using it.
The code is as follows:
Var numbers = 0.07
Var fixNum = new Number (number + 1). toFixed (1); // add 1 before rounding
Var fixedNum = new Number (fixNum-1). toFixed (1); // deduct 1 after rounding and then rounding
Console. log (fixedNum );
Http://jsfiddle.net/euvn0L1g/