1

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?

1AndOnlyPika
  • 43
  • 1
  • 7

1 Answers1

1

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));
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156