I have a requirement to be able to round numbers to either a whole number or to a specified number of decimal places….
Every now and then i find myself looking over my current solution to a problem when applying it in a new project. In this case it was very simple statistics and mean values.
For example:
const dec = [2, 678, 65.67467, 10.5452453453, 1, 0]; // Required outcome to 3 decimal places // 2, 678, 65.675, 10.545, 1, 0 // Or to 2 decimal places // 2, 678, 65.67, 10.55, 1, 0
My solution:
const round = (n, decimal = 2) => { return Math.round(n * Math.pow(10, decimal)) / Math.pow(10, decimal); };
// Quick test dec.forEach(n => { console.log(round(n, 3)); }); dec.forEach(n => { console.log(round(n)); });
As an aside: I need to have a set of numbers rounded and set with 2 fixed decimal places. So the same data set would be:
const dec = [2, 678, 65.67467, 10.5452453453, 1, 0]; // Required response would be // 2.00, 678.00, 65.67, 10.55, 1.00, 0.00
There is the Number.toFixed() method
dec.forEach(n => console.log(n.toFixed(2)));