How to Get the Integer Value from a Decimal Number in Javascript

javascript
Published on October 16, 2019

Use-Cases of this Tutorial

  • Know how to get the integer part of a decimal / float number.
  • Know how to truncate the fractional part of a number.
  • Know how to round to the next integer depending on the fractional value.

The Math.trunc() method can be used to truncate the fractional portion of a number. The number can also be rounded to the next integer using Math.round(), Math.ceil() and Math.floor() methods.

Getting the Number without Fractional Units

The Math.trunc() method simply truncates the decimal part of the number and returns the integer part.

// 11
Math.trunc(11.25)

// 11
Math.trunc(11.99)

// -11
Math.trunc(-11.25)

// 11
Math.trunc(11)

Getting the Number Rounded to the Nearest Integer

The Math.round() method rounds the number to the nearest integer.

  • If decimal part is greater than 0.5, then number is rounded to next integer which has greater absolute value. Absolute value refers to the magnitude value of the number regardless of its sign (for example 12 has greater absolute value than 11, -10 has greater absolute value than -9).
  • If decimal part is less than 0.5, then number is rounded to next integer having lower absolute value.
  • If decimal part is equal to 0.5, then number is rounded to the next greater integer.
// 11
Math.round(11.25)

// 12
Math.round(11.99)

// -11
Math.round(-11.25)

// 12
Math.round(11.5)

// -11
// round to the next greater integer
Math.round(-11.5)

// 11
Math.round(11)

Getting the Number Rounded Upwards to the Nearest Integer

Math.ceil() rounds the number upwards to the next integer (having greater value). Going by the name it returns the "ceiling" integer of a number.

// 12
Math.ceil(11.25)

// 12
Math.ceil(11.99)

// -11
// -11 has greater value than -11.25
Math.ceil(-11.25)

// 11
Math.ceil(11)

Getting the Number Rounded Downwards to the Nearest Integer

The Math.floor() method rounds the number downwards to the next integer (having lower value). Going by the name it returns the "floor" integer of a number.

// 11
Math.floor(11.25)

// 11
Math.floor(11.99)

// -12
// -12 has lower value than -11.25
Math.floor(-11.25)

// 11
Math.floor(11)
In this Tutorial