我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为double来执行一些操作。

$1,100.00→1100.00

这需要发生在所有客户端。我别无选择,只能将货币字符串作为货币字符串作为输入,但需要将其强制转换/转换为double以允许一些数学操作。


当前回答

您应该能够使用普通JS处理这个问题。国际化API是JS核心的一部分:ECMAScript国际化API https://www.w3.org/International/wiki/JavaScriptInternationalization

这个答案对我很有用:如何将数字格式化为货币字符串

其他回答

var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 
let thousands_seps = '.';
let decimal_sep = ',';

let sanitizeValue = "R$ 2.530,55".replace(thousands_seps,'')
                         .replace(decimal_sep,'.')
                         .replace(/[^0-9.-]+/, '');

// Converting to float
// Result 2530.55
let stringToFloat = parseFloat(sanitizeValue);


// Formatting for currency: "R$ 2.530,55"
// BRL in this case
let floatTocurrency = Number(stringToFloat).toLocaleString('pt-BR', {style: 'currency', currency: 'BRL'});

// Output
console.log(stringToFloat, floatTocurrency);

我知道这是一个老问题,但我想提供一个额外的选项。

jQuery Globalize提供了将特定于区域性的格式解析为float的能力。

https://github.com/jquery/globalize

给定字符串"$13,042.00",Globalize设置为en-US:

Globalize.culture("en-US");

你可以像这样解析float值:

var result = Globalize.parseFloat(Globalize.format("$13,042.00", "c"));

这将给你:

13042.00

并且允许你与其他文化一起工作。

如此令人头痛,如此少地考虑其他文化……

下面是各位:

let floatPrice = parseFloat(price.replace(/(,|\.)([0-9]{3})/g,'$2').replace(/(,|\.)/,'.'));

就这么简单。

使用正则表达式删除格式(美元和逗号),并使用parseFloat将字符串转换为浮点数。

var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;