在 JavaScript 中错误地添加两个数字

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

Adding two numbers in JavaScript incorrectly

javascript

提问by Scott

Global.alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront));

The code above outputs something like:

上面的代码输出类似:

base: 15000, upfront: 36, both: 1500036

Why is it joining the two numbers instead of adding them up?

为什么要连接两个数字而不是将它们相加?

I eventually want to set the value of another field to this amount using this:

我最终想使用这个将另一个字段的值设置为这个数量:

mainPanel.feesPanel.initialLoanAmount.setValue(Ext.util.Format.number((base + upfront), '
Global.alert(
    "base: " + base + ", upfront: " + upfront + ", both: " + 
    (parseInt(base) + parseInt(upfront))
);
,000.00'));

And when I try that, it turns the number into the millions instead of 15,036.00. Why?

当我尝试这样做时,它会将数字变成数百万而不是 15,036.00。为什么?

采纳答案by Darin Dimitrov

This might happen because they are strings. Try parsing them:

这可能会发生,因为它们是字符串。尝试解析它们:

 1 +1 == 2
"1"+1 == "11"
"1"*1 + 1 == 2

If those numbers are decimal you will need the parseFloatmethod instead.

如果这些数字是十进制的,您将需要该parseFloat方法。

回答by Phrogz

Simple example:

简单的例子:

Global.alert(
    "base: " + base + ", upfront: " + upfront + ", both: " + 
    (parseInt(base,10) + parseInt(upfront,10))
);

Ways to turn a string into a number:

将字符串转换为数字的方法:

  • parseInt(str)
  • parseInt(str,10)
  • parseFloat(str)
  • +str
  • str*1
  • str-0
  • str<<0
  • Number(str)
  • parseInt(str)
  • parseInt(str,10)
  • parseFloat(str)
  • +str
  • str*1
  • str-0
  • str<<0
  • Number(str)

And here are some of the consequences: Results of converting various strings using the above techniques
(source: phrogz.net)

以下是一些后果:( 来源:phrogz.netResults of converting various strings using the above techniques

Number(str)has the same behavior as str*1, but requires a function call.

Number(str)具有与 相同的行为str*1,但需要函数调用。

I personally use *1as it is short to type, but still stands out (unlike the unary +), and either gives me what the user typed or fails completely. I only use parseInt()when I knowthat there will be non-numeric content at the end to ignore, or when I need to parse a non-base-10 string.

我个人使用*1它,因为它打字很短,但仍然很突出(与一元 + 不同),要么给我用户输入的内容,要么完全失败。我只parseInt()在我知道最后会有非数字内容要忽略时使用,或者当我需要解析非基数为 10 的字符串时。

You can test the performance of these in your browser at my example page.

您可以在我的示例页面的浏览器测试这些性能。

回答by davidj

Try

尝试

var base = 500;
var upfront = 100;
alert("base: " + base + ", upfront: " + upfront + ", both: " + (base + upfront))

The 10 specifies base 10, otherwise the chance of the value being parsed as octal exists.

10 指定基数为 10,否则存在将值解析为八进制的机会。

回答by tau

http://jsperf.com/number-vs-parseint-vs-plus/3

http://jsperf.com/number-vs-parseint-vs-plus/3

That might also be of interest to you. It is just a performance comparison of the methods already mentioned here.

这也可能是您感兴趣的。这只是这里已经提到的方法的性能比较。

回答by Dawn

I don't know why the brackets aren't helping you out.
If I try

我不知道为什么括号没有帮助你。
如果我尝试

base + upfront + ' string' 

I do get 600 as the answer, so it could be there is something going on in the Global.alert function?

我确实得到了 600 作为答案,所以 Global.alert 函数中可能发生了一些事情?

One of the mistakes of the language design is that + is both an addition operator and a concatenation operator. Coupled with the fact that it is loosely typed and will cast implicitly means that it can give you some nasty surprises unless you take steps to ensure that you really are adding numbers and not concatenating strings. In this case, it is treating your base + upfront as strings and therefore concatenating.

语言设计的错误之一是 + 既是加法运算符又是串联运算符。再加上它是松散类型的并且会隐式转换,这意味着它会给您带来一些令人讨厌的惊喜,除非您采取措施确保您确实在添加数字而不是连接字符串。在这种情况下,它将您的基础 + 前期视为字符串,因此进行连接。

Anyway, the way around it could be to have (base - upfront*-1)instead.

无论如何,解决它的方法可能是拥有(base - upfront*-1)

回答by Mark

It's handling it as a string. You need to do your math before the string. Example:

它将它作为一个字符串处理。您需要在字符串之前进行数学运算。例子:

string + base + upfront

would return "15036 string".

将返回“15036 字符串”。

##代码##

would return string 1500036 as you are seeing now.

正如您现在看到的那样,将返回字符串 1500036。

Or use parseInt().

或者使用parseInt()