JavaScriptNumbers and Math
Math. trunc()
Cuts off the fractional part of a number, leaving the integer part.
- Returns
- The integer part of the number.
Example
#JavaScript
console.log(Math.trunc(4.9))
console.log(Math.trunc(-4.9))
console.log(Math.floor(-4.9))
console.log(Math.trunc(7.25 * 60))Console
4
-4
-5
435
Definition and usage
#The Math.trunc() function removes everything after the decimal point, without rounding. Math.trunc(4.9) is 4, and Math.trunc(-4.9) is -4.
It differs from Math.floor() with negative numbers: floor rounds down (further from zero), while trunc always rounds toward zero.
It’s a good choice when you just want to "pull out" the integer part, for example full hours from a decimal number, regardless of sign.
Syntax
#Syntax
Math.trunc(x)Parameters
#x
number
The number whose fractional part you want to cut off.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- With negative numbers, choose deliberately between
trunc(toward zero) andfloor(down). - To convert text into an integer, use
Number.parseInt(), notMath.trunc()on a string.
Related entries
#Spotted a mistake or missing an example? Write to us.