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

Javascript: Most Efficient way to convert string to integer then back to string

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

var amount = ",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 ",000.58" - the toLocaleString doesn't add back the , here?
var amount_dollar_string = "$" + amount_decimals.toLocaleString();


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

最优化的方案是不是转到第二个,然后写一个函数处理一个字符串,如果有两个以上,就把小数点后的最后一个数字截掉....?有没有更简单的方法,我做的太多了?

提前致谢!

在这两种情况下,您都可以避免调用函数 parseFloat(),方法是使用 Unary + (plus) operator which attempts to convert the operand to a number, if it is not already. And to format currency you can also use Number.prototype.toLocaleString() 作为参数传递所需的语言环境和带有选项的对象:

var amount = ',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);

不要自行设置数字格式。有一个API。

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