I have an amount field it can accept numbers like 5000 and strings like 1k,2m, 2.5k etc, so I need to convert the strings like:
1k => 1000
2m => 2000000
2.5k => 2500
And so on. How is this possible in JavaScript?
Okay, sorry about the misunderstanding.
function getVal (val) {
multiplier = val.substr(-1).toLowerCase();
if (multiplier == "k")
return parseFloat(val) * 1000;
else if (multiplier == "m")
return parseFloat(val) * 1000000;
}
Output
getVal("5.5k");
5500
getVal("2k");
2000
getVal("3.2m");
3200000
You can try:
var multipliers = {k: 1000, m: 1000000};
var string = '2.5k';
console.log(parseFloat(string)*multipliers[string.charAt(string.length-1).toLowerCase()]);
That should print 2500 from 2.5k.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.