How to convert a float to an integer in JavaScript

Last updated on Jun 16, 2021 by Suraj Sharma



In this tutorial, you will learn to convert a decimal number to a whole number in JavaScript using JavaScript Math library

Math.trunc() method can be used to remove the decimal part of the number and returns only the postive or negative integer part of the number.

Example:

Math.trunc(3.5) // 3
Math.trunc(-4.53) // -4
Math.trunc(-0.99) // -0
Math.trunc(0.89) // 0


However, few old browsers don't support theMath.trunc() method, alternatives of Math.trunc are Math.floor(), Math.ceil() or Math.round(), which converts a decimal number to its lower bound number or upper bound number respectively.

Example:

// Math.floor() examples

Math.floor(3.567) // 3
Math.floor(-3.3) // -4
Math.floor(-0.78) // -1
Math.floor(0.8) // 0

// Math.ceil() examples
Math.ceil(67.89) // 68
Math.ceil(-67.89) // 67
Math.ceil(0.56) // 1
Math.ceil(-0.78) // -0

// Math.round() examples
Math.round(67.89) // 68
Math.round(-67.5) // -67
Math.round(-0.05) // -0
Math.round(0.12) // 0


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.