Javascript:将字符串转换为整数然后返回字符串的最有效方法

时间:2016-10-27 16:58:20

标签: javascript string substring parsefloat

我有一个文本输入字段,其值为“2,000美元”之类的字符串。在我的功能中,我需要将其转换回一个数字来运行一些数学函数,然后将其作为另一个美元值吐出来,其格式为“$ 2,500.56”(I.E。不是“$ 2,500.567”)。这是我到目前为止进行的两项测试:

var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
//2000.58
var amount_integer = parseFloat(amount_no_sym);
//2000.58 (will cut out any additional decimal places)
var amount_decimals = amount_integer.toFixed(2);
//Final output is "$2,000.58" - the toLocaleString doesn't add back the , here?
var amount_dollar_string = "$" + amount_decimals.toLocaleString();


var amount = "$2,000.58"
// "2000.58"
var amount_no_sym = amount.replace(/[^\d\.]/g, '');
// 2000.58
var amount_integer = parseFloat(amount_no_sym);
//Final output is "$2,000.58"- but sometimes it will be something like "$3,564.345" for certain calculations.
var amount_dollar_string = "$" + amount_integer.toLocaleString();

最优化的解决方案是转到第二个,然后编写一个函数来处理字符串并切断小数点后的最后一个数字,如果有两个以上....?是否有更简单的方法,我做了太多工作?

提前致谢!

2 个答案:

答案 0 :(得分:2)

不要进行自己的数字格式化。有一个API。

var formatter = new Intl.NumberFormat("en-us", { style: "currency", currency: "USD" });
console.log(formatter.format(2000.58));
 

答案 1 :(得分:1)

在这两种情况下,您都可以避免使用Unary + (plus) operator调用函数parseFloat()Number.prototype.toLocaleString()尝试将操作数转换为数字(如果尚未转义)。要格式化货币,您还可以使用shouldComponentUpdate()作为参数传递所需的区域设置和带有选项的对象:

var amount = '$2,000,344.58',
    amount_integer = +amount.replace(/[^\d\.]/g, ''),
    amount_dollar_string = amount_integer.toLocaleString('en-EN', { 
      style: 'currency', 
      currency: 'USD' 
    });

console.log(amount_integer);
console.log(amount_dollar_string);