javascript 整数计算不正确
所以我正在编写一个 javascript 应用程序,基本上,如果一个数字大于另一个数字,我想交换它们的值:
if(price1 > price2)
{
var temp = price1;
price1 = price2;
price2 = temp;
}
这在某一点之前都可以正常工作,但是一旦数字开始变大,即:
price1: 12345678
price2: 234556
那么表达式将计算为 false并且什么也不做。有谁知道问题是什么?谢谢!
So I am writing a javascript application, and basically if one number is greater than another I want to swap their values:
if(price1 > price2)
{
var temp = price1;
price1 = price2;
price2 = temp;
}
This works fine up until a certain point, but once the numbers starting getting larger, i.e.:
price1: 12345678
price2: 234556
Then the expression will evaluate to false and will do nothing. Does anyone know what the issue is? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您确定这些是作为数字进行比较吗?例如,如果您将代码更改为,
它会起作用吗?如果是这样,
price1
和price2
是字符串,前缀+
将它们转换为数字。Are you sure these are being compared as numbers? For example, if you change the code to
does it work? If so
price1
andprice2
are strings and the prefix+
converts them to numbers.你确定你正在测试数字吗?
如前所述,您指定的值并没有大到足以证明此类错误的合理性。在我看来,这些值是按字典顺序(作为字符串)进行测试的。
我会相应地改变你的代码
Are you shure you are testing numbers?
As stated the values you specify are not so large to justify an error of that kind. It seems to me that the values are tested in lexicographic (as strings) order.
I would change your code accordingly
我假设
price1
和price2
是ints
。这是正确的它们应该具有
+/- 9007199254740992的精度
。I'm assuming both
price1
&price2
areints
.That to be correct they should have a precision of
+/- 9007199254740992
.