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