Javascript rounding method summary, javascript rounding
The rounding function toFixed (n) in native javascript, where n is the number of decimal places to be retained. (0 <= n <= 20)
Copy codeThe 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.
Copy codeThe 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.
Copy codeThe 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/