如何强制 Ruby 数字表现得像整数,而不是固定数字?
我有:
steven$ irb
ruby-1.9.2-p180 :001 > foo = "256MB"
=> "256MB"
ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_i
=> 256
ruby-1.9.2-p180 :003 > interim_result.class
=> Fixnum
ruby-1.9.2-p180 :004 > result = interim_result/1028
=> 0
我希望结果
为0.25
。我怎样才能做到这一点?
是否有必要/可能强制 interim_result.class
为 integer
?
请注意,以下内容并未给出所需的 0.25 结果:
ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_f
=> 256.0
ruby-1.9.2-p180 :003 > result = interim_result/1028
=> 0.2490272373540856
ruby-1.9.2-p180 :004 > result.round_to(2)
NoMethodError: undefined method `round_to' for 0.2490272373540856:Float
谢谢。
I have:
steven$ irb
ruby-1.9.2-p180 :001 > foo = "256MB"
=> "256MB"
ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_i
=> 256
ruby-1.9.2-p180 :003 > interim_result.class
=> Fixnum
ruby-1.9.2-p180 :004 > result = interim_result/1028
=> 0
I want result
to be 0.25
. How can I make this happen?
Is it necessary/possible to force interim_result.class
to be integer
?
Please note the following doesn't give the desired result of 0.25:
ruby-1.9.2-p180 :002 > interim_result = foo.slice(/\d+/).to_f
=> 256.0
ruby-1.9.2-p180 :003 > result = interim_result/1028
=> 0.2490272373540856
ruby-1.9.2-p180 :004 > result.round_to(2)
NoMethodError: undefined method `round_to' for 0.2490272373540856:Float
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,最简单的方法是在为
interim_result
赋值时调用to_f
而不是to_i
。Yes, the easiest way would be to call
to_f
instead ofto_i
when assigning a value tointerim_result
.我不太确定你的意思是表现得像一个整数。如果这是完全正确的,那么小数点后就没有任何内容了;但是,我相信您可以使用 round() 来实现您想要的。
I'm not quit sure what you mean behave like an integer. IF that was completely true you would have nothing after a decimal; however, I believe you can use
round()
to achieve what you want.只是稍微解释一下您的示例中出了什么问题。
interim_result 是正确的 256。并且会发生这种情况:
/ 带有两个fixnums(整数)是一种模除法。
为了展示它:你得到的第一个值:
一些解决方案(我更改了你的输入值。你的 256 / 1028 不是 0.25,而是 24.9.....请参阅 Codeglots 答案):
也许 Rational 是另一个不错的解决方案:
Just a litte explanation what's going wrong in your example.
interim_result is correct 256. and the this happens:
/ with two fixnums (integer) is kind of modula division.
To show it: you get the first value of:
Some solutions (I changed your entry values. your 256 / 1028 is not 0.25, but 24.9..... See Codeglots answer):
Perhaps Rational is another nice solution: