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 convert 1k, 3k, 7m, 10m, 10.2m or any formatted value into numbers using java script

I want o convert formatted currency values like:
1m
2m
3.789m
100k
20k
80.5b
etc.
into pure numbers using java script how can we achieve that?

>Solution :

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

This is not a good question (I’m sure someone in the comments will tell you that too), but I’m bored so I’ll give you the code. Here it is:

function convSuffix(str) {
  const suffix = str[str.length-1].toLowerCase();
  if (!isNaN(parseInt(suffix))) return parseInt(str);
  // If you want to allow decimials in the result, then use this 
  // instead of the previous line:
  // if (!isNaN(parseInt(suffix))) return parseFloat(str);
  
  const num = parseFloat(str.slice(0, str.length-1));
  if (suffix === 'k') return num * 1000;
  else if (suffix === 'm') return num * 1000000;
  else if (suffix === 'b') return num * 1000000000;
  else return NaN;
}

console.log(convSuffix("14")) // => 14
console.log(convSuffix("1.34b")) // => 1340000000
console.log(convSuffix("2K")) // => 2000
console.log(convSuffix("7.2m")) // => 7200000
console.log(convSuffix("7.8")) // => 7

You can add more suffixes as you see fit. If there is no suffix, it returns the value, and if it matches no suffix it returns NaN.

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