我有一个文本框,其中将有一个货币字符串,然后我需要将该字符串转换为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);
其他回答
使用正则表达式删除格式(美元和逗号),并使用parseFloat将字符串转换为浮点数。
var currency = "$1,100.00";
currency.replace(/[$,]+/g,"");
var result = parseFloat(currency) + .05;
删除所有非点/数字:
var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));
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);
我知道这是一个老问题,但CMS的答案似乎有一个小小的缺陷:它只适用于货币格式使用“。”作为小数分隔符的情况。 例如,如果你需要使用俄罗斯卢布,字符串将看起来像这样: “1 000,00搓。”
我的解决方案远不如CMS的优雅,但它应该能达到目的。
Var货币=“1 000,00搓。”;//它也适用于美式货币字符串 var cur_re = / \ D * (\ D + | \ D。* ? \ D) (?: \ D + (\ D {2})) ? \ D * $ /; Var部分= cur_re.exec(货币); var = parseFloat数量(部分[1].replace (/ \ D /,'')+'.'+( 部分[2]?部分[2]:“00”)); console.log (number.toFixed (2));
假设:
货币值采用十进制记数 字符串中没有不是货币值一部分的数字 货币值在其小数部分*中包含0或2位数字
regexp甚至可以处理“1,999美元和99美分”之类的内容,尽管它不是预期的特性,也不应该依赖它。
希望这能帮助到一些人。