EN
JavaScript - Math.trunc() method example
11 points
The Math.trunc()
method returns integer part of a number.
xxxxxxxxxx
1
console.log( Math.trunc( 5 )); // 5
2
console.log( Math.trunc( 3.14 )); // 3
3
console.log( Math.trunc( -3.14 )); // -3
4
console.log( Math.trunc( 0.123 )); // 0
5
console.log( Math.trunc( -0.123 )); // -0
6
7
console.log( Math.trunc( '+3.14' ) ); // 3.14
8
console.log( Math.trunc( '-3.14' ) ); // -3.14
9
console.log( Math.trunc( NaN ) ); // NaN
10
console.log( Math.trunc( 'foo' ) ); // NaN
11
12
console.log( Math.trunc() ); // NaN
Syntax | Math.trunc(number) |
Parameters | number - integer or float number value (primitive value). |
Result |
Integer part of If If If |
Description |
|
This example shows polyfill solution for lack of the method.
xxxxxxxxxx
1
if (Math.trunc == null) {
2
Math.trunc = function (v) {
3
return v < 0 ? Math.ceil(v) : Math.floor(v);
4
};
5
}
6
7
// Usage example:
8
9
console.log( Math.trunc( 5 )); // 5
10
console.log( Math.trunc( 3.14 )); // 3
11
console.log( Math.trunc( -3.14 )); // -3
12
console.log( Math.trunc( 0.123 )); // 0
13
console.log( Math.trunc( -0.123 )); // -0