Home > database >  How to round numbers to million, thousand, hundred, 1, 0.1, 0.01 and so on? possibly in JS?
How to round numbers to million, thousand, hundred, 1, 0.1, 0.01 and so on? possibly in JS?

Time:12-29

is there any mathematical formula for this kind of rounding? example:

1,234,567 → 1,000,000
9,321,232 → 1,000,000

12,230 → 10,000
90,000 → 10,000

1,234 → 1,000
9,000 → 1,000

9 → 1

0.12321 → 0.1
0.9123 → 0.1

0.01321 → 0.01
0.09321 → 0.01

and so on

Thank you

CodePudding user response:

Just get the most significant digit with log base 10 floored, then raise 10 to that power.

const nums = [
  1_234_567,
  9_321_232,
  12_230,
  90_000,
  1_234,
  9_000,
  9,
  0.12321,
  0.9123,
  0.01321,
  0.09321,
];

const weirdRound = (n) => 10 ** (Math.floor(Math.log10(n)));

console.log(nums.map(weirdRound));

  • Related