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

$1,100.00→1100.00

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


当前回答

这个例子运行正常

Var货币= "$1,123,456.00"; var =数量数量(currency.replace (/ [^ 0 - 9 \] + / g, " ")); console.log(数量);

其他回答

对于任何想在2021年找到解决方案的人,你都可以使用Currency.js。

经过大量研究,这是我在生产中发现的最可靠的方法,到目前为止我还没有遇到任何问题。此外,它在Github上非常活跃。

currency(123);      // 123.00
currency(1.23);     // 1.23
currency("1.23")    // 1.23
currency("$12.30")  // 12.30

var value = currency("123.45");
currency(value);    // 123.45

打印稿

import currency from "currency.js";

currency("$12.30").value;    // 12.30

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

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

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

我知道你已经找到了解决你的问题的方法,我只是想建议你看看以下更广泛的jQuery国际数字格式插件:

国际号码格式化程序

这个例子运行正常

Var货币= "$1,123,456.00"; var =数量数量(currency.replace (/ [^ 0 - 9 \] + / g, " ")); console.log(数量);

这是我的函数。适用于所有货币..

function toFloat(num) {
    dotPos = num.indexOf('.');
    commaPos = num.indexOf(',');

    if (dotPos < 0)
        dotPos = 0;

    if (commaPos < 0)
        commaPos = 0;

    if ((dotPos > commaPos) && dotPos)
        sep = dotPos;
    else {
        if ((commaPos > dotPos) && commaPos)
            sep = commaPos;
        else
            sep = false;
    }

    if (sep == false)
        return parseFloat(num.replace(/[^\d]/g, ""));

    return parseFloat(
        num.substr(0, sep).replace(/[^\d]/g, "") + '.' + 
        num.substr(sep+1, num.length).replace(/[^0-9]/, "")
    );

}

使用方法:toFloat("$1,100.00")或toFloat("$1,100.00")