admin管理员组文章数量:1342918
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?
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?
Share Improve this question edited Sep 17, 2015 at 17:53 Praveen Kumar Purushothaman 167k27 gold badges213 silver badges260 bronze badges asked Sep 17, 2015 at 17:52 chikorchikor 3872 gold badges9 silver badges20 bronze badges2 Answers
Reset to default 14Okay, 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.
本文标签: javascriptConvert string 1k string to 1000 numberStack Overflow
版权声明:本文标题:javascript - Convert string 1k string to 1000 number - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743646227a2515553.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论