In JavaScript there are a couple of ways of rounding a number. The function Math.floor
rounds the number down. It accepts a number n
and returns the biggest integer that’s less than or equal n
.
Base usage of Math.floor in JavaScript
With positive numbers it may seem as if we’re just throwing away a part of the number beyond the decimal dot.
console.log(Math.floor(7.25)); // 7
console.log(Math.floor(1.11)); // 1
console.log(Math.floor(0.99)); // 0
If you try to round the integer, it won’t change.
console.log(Math.floor(5)); // 5
console.log(Math.floor(100)); // 100
Negative numbers will be also rounded down. Not by the absolute value, though. So, you can’t just “cut by the decimal point” here.
console.log(Math.floor(-2.1)); // -3
console.log(Math.floor(-9.5)); // -10
Other data types
Technically, you can pass any value into Math.floor
. A string, a boolean, an object or even a function.
JavaScript will try to convert the incoming argument into a number. If it succeeds, then everything will continue normally.
console.log(Math.floor("2.22")); // 2
console.log(Math.floor(true)); // 1
console.log(Math.floor("-1.5")); // -2
Otherwise, the result will be NaN
— “not-a-number”.
console.log(Math.floor("hello")); // NaN
console.log(Math.floor({name: 'John', age: '25'})); // NaN
console.log(Math.floor(console.log)); // NaN
Exceptions
The values null
and undefined
behave differently. In the fist case you’ll get 0
, and in the second - NaN
.
console.log(Math.floor(null)); // 0
console.log(Math.floor(undefined)); // NaN
Remember this exception. It’s quite common on a Junior Technical Interview.
Read more JavaScript tutorials or Learn Full-Stack JS from scratch!