[Solved] Function to round number to nearest “smooth” number [closed]


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:

  1. Work out how many digits the input has
  2. Divide it by the appropriate multiple of 10
  3. Use .ceil() or .floor()
  4. Multiply by the same multiple of 10 as before

4

solved Function to round number to nearest “smooth” number [closed]