Javascript round to 2 decimal and any decimal places, with keeping or no when returning integers

Lionsure 2020-05-19 Original by the website

Javascript round decimal is implemented with the Math.round() and toFixed() methods; the former can only take the integer part, and all decimals are discarded; if you want to round the specified decimal places, you must add some auxiliary code. the latter can arbitrarily round the decimal places. The following first introduces the simple usage of Math.round() and toFixed(), and then introduces encapsulate them into methods to call directly.

 

I, The method of javascript round decimal

1. Method:

Math.round(d);//d is any valid value

NumberObject.toFixed(len);//len is the number of decimal places to be rounded

 

2. Examples of Math.round (Round to integer):

Math.round(2.4);//Output: 2

Math.round(2.5);//Output: 3

Math.round(2.44);//Output: 2

Math.round(2.54);//Output: 3

Math.round(2.455);//Output: 2

As can be seen from the output, the round() method only looks at whether the number after the decimal point is greater than or equal to 5; if it is, carries 1 to the number before it; if it is not, it does not carry 1 to the number before it regardless of whether its following numbers are greater than or equal to 5.

 

3. Examples of NumberObject.toFixed (Round to the specified number of decimal places):

var num = 2.4893;

num.toFixed(2);//Javascript round to 2 decimal places, output: 2.49

num.toFixed(3);//Javascript round to 3 decimal places, output: 2.489

num.toFixed(1);//Javascript round to 1 decimal place, output: 2.5

 

 

II, How to round off decimal numbers in javascript, it does not keep decimal places when returning integers

Math.round() can not keep decimal places, so to keep the specified decimal places (such as 2, 3, etc.), but also add a few codes, the implementation method is as follows:

//When returning an integer, no decimal places are kept, for example, 2.999, 2 decimal places are reserved, and 3 is returned
       //num: value to be rounded, len: decimal places are kept
       function GetRound(num, len) {
              return Math.round(num * Math.pow(10, len)) / Math.pow(10, len);
       }

 

Call:

GetRound(2.999, 2);//Round to 2 decimal places, return 3

GetRound(2.989, 2);//Round to 2 decimal places, return 2.99

 

 

III, Javascript round decimal keeps decimal places in any case

//Round to the specified decimal places, for example, 2.999, round to 2 decimal places, return 3.00
       //num: value to be rounded, len: decimal places are kept
       function GetRoundDd(num, len) {
              return num.toFixed(len);
       }

 

Call:

GetRoundDd(2.999, 2);//Round to 2 decimal places, return 3.00

GetRoundDd(2.989, 2);//Round to 2 decimal places, return 2.99