js rounding

https://www.cnblogs.com/xishaohui/p/7728032.html

1. Tofixed method

  The toFixed() method rounds a Number to the specified number of decimal places. For example, if the data Num is kept to 2 decimal places, it is expressed as: toFixed(Num); but its rounding rules are different from those in mathematics. The banker's rounding rule is used, and the banker's rounding: the so-called banker's rounding method , the essence of which is a method of rounding up to five pairs (also known as rounding up to five and leaving doubles). The specific rules are as follows:

To put it simply: round up to five. If the number after five is non-zero, add one. If the number after five is zero, it should be rounded up. If it is even before five, it should be rounded up.

Obviously this rule doesn't fit the way we usually deal with data. In order to solve such a problem, you can customize the Math.round method to specify how many bits of data to keep for processing.

2, round method

  The round() method rounds a number to the nearest integer. For example: Math.round(x), it will take x to the nearest integer. The method of choosing and rounding uses the method of rounding, which conforms to the rules of choosing and 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.

3. Combining the two methods

  If you want to force two decimal places after rounding, that is, 12-12.00, use the two methods in combination ( Math.round(X * 100) / 100 ).tofixed(2);

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325268643&siteId=291194637