Home >Web Front-end >JS Tutorial >Detailed explanation of JS processing data rounding
This article mainly brings you an article about JS processing data rounding (detailed explanation of the difference between tofixed and round). The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.
1, tofixed method
toFixed() method can round Number to a number with specified 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 , its essence is a method of rounding up to five to get even (also known as rounding up 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, look at the odd or even number. If the number before five is even, it should be discarded. If the number before five is odd, it should be discarded. Further.
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
round() method can round 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.
Related recommendations:
php method to save two decimal places and round
3 ways to achieve rounding in PHP
The above is the detailed content of Detailed explanation of JS processing data rounding. For more information, please follow other related articles on the PHP Chinese website!