- #javaScript
- #snippets
The problem to solve is how to round an array of decimal numbers down to whole integers. The numbers variable points to such an array.
const numbers = [1.2, 2.49, 3.5, 5.7]
The Math.round() method should solve the problem. Let’s see.
let rounded = []
numbers.forEach(n => rounded.push(Math.round(n)))
// rounded [1, 2, 4, 6]
The result is not quite what we want. The decimals below .5 are rounded down to the nearest integer whereas the decimals above .5 are rounded up.
Instead let’s try the Math.floor() method.
let floored = []
numbers.forEach(n => floored.push(Math.floor(n)))
// floored [1, 2, 3, 5]
This works a treat. Therefore, to round a decimal number down to a whole integer use the Math.floor() method.
Thank you for stumbling across this website and for reading my blog post entitled Round a decimal number down with JavaScript