Ruby 1.8.6 BigDecimal.to_f 始终返回 '0,0'在 Solaris 上
我遇到了一个非常奇怪的错误。我在 Solaris 10 上,使用 Ruby Enterprise Edition(ruby 1.8.6 (2008-08-08 patchlevel 286) [i386-solaris2.10])和 Rails 2.3.4。我有一个非常奇怪的错误。在irb中:
irb(main):001:0> require 'bigdecimal'
=> true
irb(main):002:0> b = BigDecimal.new('123')
=> #<BigDecimal:834d0e8,'0.123E3',4(8)>
irb(main):003:0> b.to_s
=> "0.123E3"
irb(main):004:0> b.to_i
=> 123
irb(main):005:0> b.to_f
=> 123.0
irb(main):006:0>
一切都很好!但是当我启动 Rails 控制台并执行相同的操作时,“to_f”总是返回“0,0”。
>> b = BigDecimal.new('123')
=> #<BigDecimal:9e80e14,'0.123E3',4(8)>
>> b.to_s
=> "123.0"
>> b.to_i
=> 123
>> b.to_f
=> 0,0
当我在 Mac 上执行同样的操作时,不会发生这种情况。很奇怪!这可能是 Ruby 企业版中的一个错误吗?但如果是这样,为什么 irb 不会出现这种情况(这也是 REE 版本,我仔细检查过)。有什么想法吗?
- 约翰内斯
I have come across a very weird error. I'm on Solaris 10, using Ruby Enterprise Edition (ruby 1.8.6 (2008-08-08 patchlevel 286) [i386-solaris2.10]) with Rails 2.3.4. I have a very weird error. In irb:
irb(main):001:0> require 'bigdecimal'
=> true
irb(main):002:0> b = BigDecimal.new('123')
=> #<BigDecimal:834d0e8,'0.123E3',4(8)>
irb(main):003:0> b.to_s
=> "0.123E3"
irb(main):004:0> b.to_i
=> 123
irb(main):005:0> b.to_f
=> 123.0
irb(main):006:0>
Everything's fine! BUT when I fire up the Rails console and do the same thing, "to_f" always returns '0,0'.
>> b = BigDecimal.new('123')
=> #<BigDecimal:9e80e14,'0.123E3',4(8)>
>> b.to_s
=> "123.0"
>> b.to_i
=> 123
>> b.to_f
=> 0,0
This does not happen when I do the same thing on my Mac. Very weird! Is that possibly a bug in Ruby Enterprise Edition? But if so, why doesn't it occur with irb (which also is the REE version, I double checked). Any ideas?
- Johannes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不是专家,但我的猜测是这种行为是你在德国的副作用。
显然,to_f 使用国家化版本的小数分隔符。我怀疑如果您将计算机的国籍设置更改为美国,情况将会改变。
编辑:
这并不能帮助您解决问题。但更多的背景信息可能是:
当你在 irb 中执行
123.to_f
时,你实际上是在执行123.to_f.to_s
(因为 irb 需要打印出你的结果)。使用格式运算符
%
进行显式格式化可能会更好:"%5.1f" % 123 => 123.0
编辑:
经过一番挖掘,在这里找到了一些真正相关且有用的信息:
http://rubyforge.org/forum/forum.php?thread_id=32460&forum_id=723
这是 Ruby 社区中已知的问题,但不会被解决“固定”本身。线程中提供了解决方法。
I'm no expert, but my guess is that this behavior is a side effect of your being in Germany.
Apparently, to_f uses a nationalized version of the decimal separator. I suspect that if you change your computer's nationality settings to US, this will change.
EDIT:
Not that this helps your problem. But a little more background info might:
When you do
123.to_f
in irb, you're actually executing123.to_f.to_s
(because irb needs to print out your result).You might be better served with explicit formatting using the format operator
%
:"%5.1f" % 123 => 123.0
EDIT:
After some digging, found some truly relevant and helpful information here:
http://rubyforge.org/forum/forum.php?thread_id=32460&forum_id=723
It's a problem that's known in the Ruby community, but will not be "fixed" as such. Workarounds are provided in the thread.