Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading