Languages
[Edit]
EN

JavaScript - Math.trunc() method example

11 points
Created by:
Marcin
2441

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

SyntaxMath.trunc(number)
Parametersnumber - integer or float number value (primitive value).
Result

Integer part of number value  (primitive value).

If number is NaN it returns NaN.

If number is -Infinity it returns -Infinity.

If number is +Infinity it returns +Infinity.

Description

Math.trunc() is a static method that takes one parameter and returns integer part of number passed as argument. Integer numbers are returned without any changes.

Note: this method has been introduced in ES 2015.

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

References

  1. Truncation - Wikipedia

Checkout latest findings & news:

Checkout latest questions:

Checkout latest wiki articles:

JavaScript - Math (EN)

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Rockstar community members
Thank you for great work 👍