javascript jquery 添加十进制数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10817479/
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 11:08:26  来源:igfitidea点击:

jquery adding decimal numbers

javascriptjquery

提问by user892134

I'm trying to add together decimal numbers but when i alert the variable finalnumberi get zero. The variable numberis a decimal number. How do i solve this so that variable finalnumberis the sum of all number?

我试图将十进制数加在一起,但是当我提醒变量时,finalnumber我得到零。变量number是一个十进制数。我如何解决这个问题,以便变量finalnumber是所有的总和number

var finalnumber = 0;

$('#chosen-keyword-container').find('.keyword-row').each(function() {
    var number = $(this).find('td:last').find('input[name=bid-price[]]').val();

    var finalnumber = parseInt(number) + parseInt(finalnumber);

});?

回答by gdoron is supporting Monica

Change this:

改变这个:

var finalnumber = parseInt(number)+parseInt(finalnumber);  

To this:

对此:

finalnumber = finalnumber + parseFloat(number); 

Or:

或者:

finalnumber += parseFloat(number); 
  • parseIntcan't hold decimal values. use parseFloatinstead.
  • Don't declare finalnumberwith var, becuase it hides the finalnumberin the outer scope.
  • parseInt不能保存十进制值。使用parseFloat来代替。
  • 不要声明finalnumberwith var,因为它隐藏finalnumber在外部作用域中。

回答by Sirko

Just drop the varkeyword inside your function in front of finalnumber. With that varyou define a new variable under that name and scope. So basically you have two versions of finalnumberand just add to the local one (the one inside the function and not the global one).

只需var将函数内的关键字放在finalnumber. 有了它,var您可以在该名称和范围下定义一个新变量。所以基本上你有两个版本,finalnumber只是添加到本地一个(函数内部的一个而不是全局一个)。

On the other hand you should change parseIntto parseFloatas you are working with decimal numbers (See answer of @gdoron).

在另一方面,你应该改变parseInt,以parseFloat作为您与十进制数(@gdoron的见的答案)工作。

$('#chosen-keyword-container').find('.keyword-row').each(function() {
  var number = $(this).find('td:last').find('input[name=bid-price[]]').val();

  finalnumber = parseFloat(number) + finalnumber;  
});

On a sidenote: You can drop the parseInt()inside the function for finalnumber. This variable is always a number value and so there is no need to convert it.

在阿里纳斯:你可以删除parseInt()的功能里面finalnumber。此变量始终是一个数值,因此无需对其进行转换。

回答by rt2800

change the addition line as follows

更改添加行如下

finalnumber = finalnumber + parseFloat(number);