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?
CodePudding user response:
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
.