Javascript round number(4 methods), with rounding to integer and getting the integer part

Lionsure 2020-06-22 Original by the website

In the process of website development, sometimes decimals are rounded a number. In order to facilitate this operation, javascript also provides four methods, namely: round(), ceil(), floor() and parseInt(). The round() is used to round to integer, ceil() is used to round up, floor() is used to round down, and parseInt() is used to only take the integer part.

 

1. Javascript round to integer(Javascript round a number)

If you need to round decimal to integer, use the Math.round() method, for example:

function GetRoundNumber(n){
              return Math.round(n);
       }

Call: GetRoundNumber(12.56);

Output result: 13

 

2. Javascript round number with ceil()

The Math.ceil() method is to take the ceiling, i.e. round up, find the smallest integer but not less than itself, for example:

function GetCeilNumber(n){
              return Math.ceil(n);
       }

Call: GetCeilNumber(12.56); GetCeilNumber(-12.56);

Output result: 13; -12

 

3. Javascript round number with floor()

The Math.floor() method is to take the floor, that is, round down, find the largest integer but not greater than itself, for example:

function GetFloorNumber(n){
              return Math.floor(n);
       }

Call: GetFloorNumber(12.56); GetFloorNumber(-12.56);

Output result: 12; -13

 

4. Javascript round number with parseInt() to only get integer part

The Math.parseInt() method is to get only the integer part, that is, regardless of whether the number after the decimal point is greater than 5, it will be discarded, for example:

function GetInt(n){
              return Math.parseInt(n);
       }

Call: GetInt(12.56); GetInt(-12.56);

Output result: 12; -12