Languages
[Edit]
EN

JavaScript - Math.floor() method example

14 points
Created by:
Root-ssh
175020

The Math.floor() function returns an integer value that is smaller than or equal to the argument - the result of round down operation.  

// ONLINE-RUNNER:browser;

console.log( Math.floor(  5     ) ); //  5

console.log( Math.floor(  2.49  ) ); //  2
console.log( Math.floor(  2.50  ) ); //  2
console.log( Math.floor(  2.51  ) ); //  2

console.log( Math.floor( -2.49  ) ); // -3
console.log( Math.floor( -2.50  ) ); // -3
console.log( Math.floor( -2.51  ) ); // -3

console.log( Math.floor(  0.999 ) ); //  0
console.log( Math.floor(  1.001 ) ); //  1
console.log( Math.floor( -1.001 ) ); // -2

1. Documentation

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

Rounded down number value (primitive value).

If number value is equal to NaN it returns NaN.

If number value is equal to -Infinity it returns -Infinity.

If number value is equal to +Infinity it returns +Infinity.

Descriptionfloor is a static method that takes only one parameter and returns a rounded-down value.

2. Rounding with precision down-to n places example

// ONLINE-RUNNER:browser;

function floorPrecised(number, precision) {
	var power = Math.pow(10, precision);

  	return Math.floor(number * power) / power;
}

// Example:

console.log( floorPrecised(     5  ,  0 ) ); // 5
console.log( floorPrecised(     5. ,  0 ) ); // 5
console.log( floorPrecised(      .5,  0 ) ); // 0

console.log( floorPrecised(  1.1234,  0 ) ); // 1
console.log( floorPrecised(  1.1234,  1 ) ); // 1.1
console.log( floorPrecised(  1.1235,  2 ) ); // 1.12
console.log( floorPrecised(  1.1235,  3 ) ); // 1.123

console.log( floorPrecised( -1.1234,  0 ) ); // -2
console.log( floorPrecised( -1.1234,  1 ) ); // -1.2
console.log( floorPrecised( -1.1234,  2 ) ); // -1.13
console.log( floorPrecised( -1.1234,  3 ) ); // -1.124
 
console.log( floorPrecised(    1234, -1 ) ); // 1230
console.log( floorPrecised(    1234, -2 ) ); // 1200
console.log( floorPrecised(    1234, -3 ) ); // 1000

console.log( floorPrecised(  5_000.000_001,  0 ) ); // 5000
console.log( floorPrecised(  5_000.000_001,  6 ) ); // 5000.000001
console.log( floorPrecised(  5_000.000_001, -3 ) ); // 5000

References

  1. Floor and ceiling functions - Wikipedia

Alternative titles

  1. JavaScript - Math.floor() documentation with examples
  2. js - Math.floor() method documentation with examples
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - Math documentation (EN)

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join