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_res开发者_如何学运维ult = 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.
Yes, the easiest way would be to call to_f
instead of to_i
when assigning a value to interim_result
.
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.
ruby-1.9.2-p180-mri :001 > a = 0.2490272373540856
=> 0.2490272373540856
ruby-1.9.2-p180-mri :002 > a.round(2)
=> 0.25
ruby-1.9.2-p180-mri :003 >
Just a litte explanation what's going wrong in your example.
interim_result is correct 256. and the this happens:
256 / 1024 #-> 0
/ with two fixnums (integer) is kind of modula division. To show it: you get the first value of:
256.divmod(1024)#-> [0, 256]
256.divmod(1024).first #-> 0
Some solutions (I changed your entry values. your 256 / 1028 is not 0.25, but 24.9..... See Codeglots answer):
256 / 1024.0 #-> 0.25
Perhaps Rational is another nice solution:
256 / Rational(1024,1) #-> (1/4)
256 * Rational(1,1024) #-> (1/4)
精彩评论