Reputation: 99970
I am trying to round numbers to a certain decimal place, the expected API would be something like this:
const rounded = Math.round(1.6180339, 5);
or
const rounded = new Number(1.6180339).round(5);
but those APIs don't seem to exist. I have this which appears to work as is:
const [
e,
π,
φ
] = [
2.71828182845904,
3.14159265358979,
1.61803398874989,
];
console.log(
Number(e.toFixed(5)) === 2.71828 // true
);
console.log(
Number(e.toFixed(3)) === 2.718 // true
);
console.log(
Number(e.toFixed(3)) === 2.7182 // false
);
console.log(
Number(e.toFixed(3)) === 2.71 // false
);
this works, but we have to use toFixed() which converts number to a string first. Is there a way to round a number directly without converting to a string?
Upvotes: 0
Views: 354
Reputation: 1976
Like mentioned in comments, floating point operations can be a pain with javascript. Anyway, you can still build a tool like this one that relies on powers of 10 to perform roundings and avoid string conversion step :
const Rounder = {
floor(n, m) {
return Math.floor(n * Math.pow(10, m)) / Math.pow(10, m);
},
ceil(n, m) {
return Math.ceil(n * Math.pow(10, m)) / Math.pow(10, m);
},
round(n, m) {
return Math.round(n * Math.pow(10, m)) / Math.pow(10, m);
}
}
console.log(Rounder.ceil(7.1812828, 3));
console.log(Rounder.floor(7.1812828, 5));
console.log(Rounder.round(7.1812828, 2));
console.log(Rounder.round(0.11111111111, 8));
console.log(Rounder.ceil(0.11111111111, 8));
Upvotes: 2