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?
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 :