The trunc() method truncates (shortens) a number and returns its integer portion.
Example
trunc() Syntax
The syntax of the Math.trunc() method is:
Math.trunc(number)
Here, trunc() is a static method. Hence, we are accessing the method using the class name, Math.
trunc() Parameter
The trunc() method takes a single parameter:
number- value that needs to be truncated (shortened to integer)
trunc() Return Value
The trunc() method returns:
- integer part of a
number - NaN (Not a Number) for a non-numeric argument
Example 1: JavaScript Math.trunc()
Here, the Math.trunc() returns
- -50 - for the negative number
-50.45627 - 18 - for the positive number
18.645
Note: The trunc() method does not round off a number, it just removes the digits after the decimal point and returns the integer portion.
Example 2: JavaScript Math.trunc() with Numeric String
In the above example, Math.trunc("15.645") converts the numeric string to a number and truncates it.
Example 3: JavaScript Math.trunc() with Non-Numeric Argument
In the above example, we have used the trunc() method with a string argument "Luke". That's why we get NaN as output.
Recommended readings: