how to convert integer in to specific string based on value [closed]

I have different users in a sqlite db, and I want a way to convert them to a string based on the amount.

Lets say I have user 1 with 10000x which would be converted into 10K. Or user 2 with 500000x which will be converted into 500K, or user 3 with 10500000 which will be converted into 10.5M. How would I do that?

Answers:

Answer

A little bit of math will get you there:

const convert = (n) => {
  const units = ['', 'K', 'M', 'G', 'T', 'P'];
  const p = Math.floor(Math.log10(n) / 3);
  
  return n / Math.pow(10, p * 3) + units[p];
};

console.log(convert(1000));
console.log(convert(50000));
console.log(convert(10500000));

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.