我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为double来执行一些操作。
$1,100.00→1100.00
这需要发生在所有客户端。我别无选择,只能将货币字符串作为货币字符串作为输入,但需要将其强制转换/转换为double以允许一些数学操作。
我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为double来执行一些操作。
$1,100.00→1100.00
这需要发生在所有客户端。我别无选择,只能将货币字符串作为货币字符串作为输入,但需要将其强制转换/转换为double以允许一些数学操作。
当前回答
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
并且允许你与其他文化一起工作。
function NumberConvertToDecimal (number) {
if (number == 0) {
return '0.00';
}
number = parseFloat(number);
number = number.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1");
number = number.split('.').join('*').split('*').join('.');
return number;
}
jQuery.preferCulture("en-IN");
var price = jQuery.format(39.00, "c");
输出为:39.00卢比
use jquery.glob.js,
jQuery.glob.all.js
这是我的函数。适用于所有货币..
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")
简单地说
Number(currency.replace(/[^0-9-]+/g,""))/100;
适用于所有货币和地区。替换所有非数字字符(您可以有€50.000,00或$50,000.00)输入必须有2位小数