最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert string 1k string to 1000 number - Stack Overflow

programmeradmin1浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 14

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.

发布评论

评论列表(0)

  1. 暂无评论