OPTION 1
You could use .toPrecision()
It is explained in more detail here but basically you can specify the number of significant figures, e.g.
function precise(x) {
return Number.parseFloat(x).toPrecision(1);
}
console.log(precise(54));
// output: "50"
console.log(precise(2051075640));
// output: "2000000000 "
console.log(precise('99.999'));
// output: "100"
OPTION 2
If you wanted to always round up or always round down, you could use .ceil()
and/or .floor()
Note: these round to the nearest integer but you could process the input to utilize them:
- Work out how many digits the input has
- Divide it by the appropriate multiple of 10
- Use
.ceil()
or.floor()
- Multiply by the same multiple of 10 as before
4
solved Function to round number to nearest “smooth” number [closed]