TakaGoto
TakaGoto

Reputation: 362

Binary fraction in ruby

I want to change a floating number to binary form, for example for 12.345. I got the integer part done:

(12.345).floor.to_s(2) #=> 1100

for the fraction, however, can't find the best way to do this.

I do have a way, the way Wikipedia shows here, but It's a very long process: a while loop with a bunch of temporary variables that I want to avoid. I was wondering if there is a better way to do this it in Ruby.

The full binary form I want to get is 1100.011 in string form.

Upvotes: 2

Views: 271

Answers (1)

sawa
sawa

Reputation: 168091

You can multiply it with a large-enough power of 2 (say 2 ** 10), then convert it to binary, and then insert the decimal point back.

(12.345 * 2 ** 10).to_i.to_s(2).insert(-(10 + 1), ".")
# => => "1100.0101100001"

By the way, I don't think 1100.011 is the correct form.

Upvotes: 2

Related Questions