I try to do:
a=1.5
puts a.to_s(2)
But it does not work
Any suggestions please, since I do not even know the name of the digits that go after the point I know by decimals but I do not think that is the case
I try to do:
a=1.5
puts a.to_s(2)
But it does not work
Any suggestions please, since I do not even know the name of the digits that go after the point I know by decimals but I do not think that is the case
With Ruby you can not convert numbers with decimals (i.e. of class Float
) to binary with to_s
, because that method does not exist in class Float
.
However you can create a method to do it, for example:
def float_to_binary(float)
int, dec = float.divmod(1)
bin = "#{int.to_s(2)}."
while dec > 0
int, dec = (dec * 2).divmod(1)
bin << int.to_s
end
bin
end
Test:
a = 1.5
float_to_binary(a)
#=> "1.1"
The method can probably be optimized a bit, but this code is functional and achieves the expected result.