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

$1,100.00→1100.00

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


当前回答

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;
} 

其他回答

删除所有非点/数字:

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));

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

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")

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

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

jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");

输出为:39.00卢比

use jquery.glob.js,
    jQuery.glob.all.js

这个例子运行正常

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