javascript 如何使用jquery对货币格式的数字求和

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12170638/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:29:12  来源:igfitidea点击:

How to sum numbers that are in currency format using jquery

javascriptjquerycurrency

提问by black_belt

I am trying to sum up the following numbers.

我试图总结以下数字。

 var number1= 12,000.00 ;  var number2= 12,000.00;

I have tried this alert(number1+number2);?but it doesn't return any data.

我试过这个,alert(number1+number2);?但它不返回任何数据。

Could you please help me to solve this problem?

你能帮我解决这个问题吗?

Thanks

谢谢

回答by nbrooks

The code in your question is invalid javascript. You can't have a ,inside a numeric literal. You have to store it as a string, then parse it manually:

您问题中的代码是无效的 javascript。您不能,在数字文字内部使用 a 。您必须将其存储为字符串,然后手动解析它:

var number1 = '12,000.00';
var number2 = '12,000.00';

function parseCurrency( num ) {
    return parseFloat( num.replace( /,/g, '') );
}

alert( parseCurrency(number1) + parseCurrency(number2) );

回答by imsky

This won't work. Use accounting.js's unformatfunction to parse 12,000 as a string instead.

这行不通。使用accounting.jsunformat函数将 12,000 解析为字符串。