How do I convert the decimal number 1.5 to binary 1.1 in ruby?

0

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

    
asked by antonio gonzalez 26.07.2017 в 22:22
source

1 answer

0

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.

    
answered by 27.07.2017 в 00:04