简体   繁体   English

BigDecimal to_s与to_f不匹配

[英]BigDecimal to_s does not match to_f

Is the BigDecimal class broken? BigDecimal类是否已损坏? It seems like the following should never, ever occur: Note that a.to_f != a.to_s.to_f 似乎永远不会发生以下情况:注意a.to_f!= a.to_s.to_f

a.class => BigDecimal a.class => BigDecimal

a.to_f => 18658.1072928 a.to_f => 18658.1072928

a.to_s => "10865.81072928" a.to_s =>“10865.81072928”

b.class => BigDecimal b.class => BigDecimal

b.to_f => 10000.0 b.to_f => 10000.0

b.to_s => "10000.0" b.to_s =>“10000.0”

(a - b).to_f => 865.81072928 (a - b).to_f => 865.81072928

a.to_f - b.to_f => 8658.1072928 a.to_f - b.to_f => 8658.1072928

Any ideas as to what might be going wrong? 关于可能出错的任何想法? We are running ruby 1.8.7p72 on our servers and 1.8.7p173 on our local machines. 我们在服务器上运行ruby 1.8.7p72,在本地机器上运行1.8.7p173。

If you're running Mac OS X 10.6.3 then this might be an explanation: http://www.abletech.co.nz/2010/03/osx-10-6-3-installs-new-ruby-with-faulty-bigdecimal/ 如果您运行的是Mac OS X 10.6.3,那么这可能是一个解释: http//www.abletech.co.nz/2010/03/osx-10-6-3-installs-new-ruby-with-故障-的BigDecimal /

To get rid of the problem you could use RVM . 要摆脱这个问题,你可以使用RVM

As the docs say: 正如文档所说:

to_f : to_f

Returns a new Float object having approximately the same value as the BigDecimal number. 返回一个新的Float对象,其值与BigDecimal数字大致相同。 Normal accuracy limits and built-in errors of binary Float arithmetic apply. 适用二进制浮点运算的正常精度限制和内置错误。

That means that Float in ruby behaves just like a float everywhere: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems 这意味着Ruby中的Float就像一个浮动的地方: http//en.wikipedia.org/wiki/Floating_point#Accuracy_problems

Not every number is representable by a Float. 并非每个数字都可以由Float表示。 In such cases the number is rounded. 在这种情况下,数字是四舍五入的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM