gpt4 book ai didi

Ruby - 添加负浮点值

转载 作者:数据小太阳 更新时间:2023-10-29 08:50:54 25 4
gpt4 key购买 nike

我是 Ruby 的新手,所以我首先为我的无知道歉 :) 我在对客户的帐户进行总计时发现了一个问题。有些金额是带小数位的负数,这会破坏总数。这是一些简单的示例代码...

testnum = 0.00
puts "###Debug### testnum = #{testnum} (after 0.00)"
testnum += 5.00
puts "###Debug### testnum = #{testnum} (after 5.00)"
testnum += 3.33
puts "###Debug### testnum = #{testnum} (after 3.33)"
testnum += -1.00
puts "###Debug### testnum = #{testnum} (after -1.00)"
testnum += -2.22
puts "###Debug### testnum = #{testnum} (after -2.22)"

结果...

###Debug### testnum = 0.0 (after  0.00)
###Debug### testnum = 5.0 (after 5.00)
###Debug### testnum = 8.33 (after 3.33)
###Debug### testnum = 7.33 (after -1.00)
###Debug### testnum = 5.109999999999999 (after -2.22)

所以 testnum 在添加 -2.22 后损坏,但添加 -1.00 没问题。不确定我做错了什么。

最佳答案

来自 http://floating-point-gui.de/basic/

Why don’t my numbers, like 0.1 + 0.2 add up to a nice round 0.3, and instead I get a weird result like 0.30000000000000004?

Because internally, computers use a format (binary floating-point) that cannot accurately represent a number like 0.1, 0.2 or 0.3 at all.

If you really need your results to add up exactly, especially when you work with money: use a special decimal datatype.

在 Ruby 中,这是 BigDecimal

关于Ruby - 添加负浮点值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13287427/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com