javascript 计算 123+Math.floor(123*0.008*100)/100+10 为什么等于 133.98000000000002 ?

2017-03-15 19:32:28 +08:00
 gdtv


-------------------------

更新:感谢1楼的指点,改成了这样:(123*100+Math.floor(123*0.008*100)+10*100)/100=133.98,不知有没有更好的方法?

PS: 为什么markdown模式显示不出星号?
2930 次点击
所在节点    JavaScript
16 条回复
jingniao
2017-03-15 19:33:50 +08:00
典型的浮点数问题
Reficul
2017-03-15 19:46:40 +08:00
0.1+0.2!=0.3 ,浮点数无解。只能想办法减少误差
0915240
2017-03-15 19:50:34 +08:00
这个礼拜的第二回了:

http://0.30000000000000004.com/
IamJ
2017-03-15 19:54:38 +08:00
@0915240 这域名 666
nyanyh
2017-03-15 20:41:13 +08:00
r#3 @0915240 这域名哈哈哈哈哈哈哈哈哈哈哈哈
mcfog
2017-03-15 20:48:32 +08:00
不用那么长,我也来个短的 0.58*100
Shura
2017-03-15 20:49:29 +08:00
建议楼主去学习一下计算机组成原理(
SoloCompany
2017-03-15 21:56:43 +08:00
一大谜团 - 为啥楼主不用 append 也能编辑帖子?
Mutoo
2017-03-15 22:00:51 +08:00
keyword: IEEE 754 浮点数计算
SoloCompany
2017-03-15 22:04:04 +08:00
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round#Decimal_rounding

然后你可以试一下
Math.round10(123+Math.floor(123*0.008*100)/100+10, -10)
misaka19000
2017-03-15 22:10:23 +08:00
Quaintjade
2017-03-15 22:38:23 +08:00
@SoloCompany
Mozilla 这个还只是一半,负数部分得自己写,因为 js 的 Math.Round()总是向正无穷大取整:
If the fractional portion is exactly 0.5, the argument is rounded to the next integer in the direction of +∞

比如 Math.round10(-1.005,-2)的结果是 -1 而不是 -1.01
wly19960911
2017-03-15 22:47:06 +08:00
@SoloCompany 我没记错的话,短时间内能编辑的,
codelegant
2017-03-15 23:06:58 +08:00
@0915240 这个网站,的确非常的有意思。
a87150
2017-03-15 23:09:27 +08:00
世界的错
zhuziyi
2017-03-16 00:00:41 +08:00
![]( )

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/347717

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX