This time I will bring you a detailed explanation of the use of tofixed and round in JS. What are the precautions for using tofixed and round in JS. The following is a practical case. Let’s take a look. .
1, tofixed method
The toFixed() method rounds a Number to a specified number of decimal places. For example, if the data Num is kept to 2 decimal places, it is expressed as: toFixed(Num); however, the rounding rules are different from those in mathematics. The banker's rounding rule is used, Banker's rounding: The so-called banker's rounding method is essentially a method of rounding to five and leaving even (also known as rounding to five and leaving even). The specific rules are as follows:
To put it simply: consider rounding up to five. If the number after five is not zero, add one. If the number after five is zero, it should be odd or even. If the number before five is even, it should be discarded. If the number before five is odd, it should be rounded by one.
Obviously this rule does not conform to the way we usually deal with data. In order to solve this problem, you can customize the implementation using the Math.round method to specify how many bits of data to retain for processing.
2, round method
The round() method rounds a number to the nearest integer. For example: Math.round(x) takes x to the nearest integer. The rounding method is used in the rounding method, which conforms to the rules of rounding in mathematics. The processing of decimals is not so convenient, but it can be customized according to different requirements.
For example: To process X with two decimal places, you can use Math.round(X * 100) / 100. for processing.
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Bootrap Vue implements Baidu search interface function
webpack3 loader usage analysis
The above is the detailed content of Detailed explanation of the use of tofixed and round in JS. For more information, please follow other related articles on the PHP Chinese website!