我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为double来执行一些操作。
$1,100.00→1100.00
这需要发生在所有客户端。我别无选择,只能将货币字符串作为货币字符串作为输入,但需要将其强制转换/转换为double以允许一些数学操作。
我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为double来执行一些操作。
$1,100.00→1100.00
这需要发生在所有客户端。我别无选择,只能将货币字符串作为货币字符串作为输入,但需要将其强制转换/转换为double以允许一些数学操作。
当前回答
我知道你已经找到了解决你的问题的方法,我只是想建议你看看以下更广泛的jQuery国际数字格式插件:
国际号码格式化程序
其他回答
js是正确的方法。我在一个项目中使用过它,并有很好的使用经验。
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000
你可以在GitHub上找到它
这个函数应该适用于任何语言环境和货币设置:
function getNumPrice(price, decimalpoint) {
var p = price.split(decimalpoint);
for (var i=0;i<p.length;i++) p[i] = p[i].replace(/\D/g,'');
return p.join('.');
}
这假设您知道小数点字符(在我的例子中,区域设置来自PHP,所以我用<?PHP返回cms_function_to_get_decimal_point();? >)。
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);
删除所有非点/数字:
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")