JS:如何在 javascript 中添加负数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22064579/
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
JS: How to add negative numbers in javascript
提问by Growlithe
supposing I have variable ex1
equal to -20 and variable ex2
equal to 50. I try to add it in javascript as alert(ex1+ex2);
but it alerts -20+50
. I'm really confused with this. THanks for the help, even though it might be a really silly question.
假设我有一个ex1
等于 -20 的变量和ex2
等于 50 的变量。我尝试将它添加到 javascript 中,alert(ex1+ex2);
但它会发出警报-20+50
。我真的很困惑。感谢您的帮助,即使这可能是一个非常愚蠢的问题。
回答by thefourtheye
JavaScript is a weakly typed language. So, you have to be careful with the types of data which you use. Without knowing much about your program, this can be fixed like this
JavaScript 是一种弱类型语言。因此,您必须小心使用的数据类型。在不了解您的程序的情况下,可以像这样修复
alert(parseInt(ex1, 10) + parseInt(ex2, 10));
This makes sure that both ex1
and ex2
are integers. If you think, you would be using floating point numbers
这确保了ex1
和ex2
都是整数。如果您认为,您将使用浮点数
alert(parseFloat(ex1) + parseFloat(ex2));
回答by MusicLovingIndianGirl
Change your code like this
像这样改变你的代码
alert(parseInt(ex1) + parseInt(ex2));