Fractional

Fractional is a library for parsing, representing and operating on fractions.

Conversions

Convert fractional strings to floats:

Fractional.new("1100 7/8").to_f #=> 1100.875

Convert floats to fractional strings:

Fractional.new(1100.875).to_s   #=> "1100 7/8"
Fractional.new(1100.875, :to_nearest => "1/2").to_s #=> "1101"

Also does a great job of guessing repeating decimal values:

Fractional.new(0.33333).to_s    #=> "1/3"
Fractional.new(3.142857142857).to_s    #=> "22/7"

If you want to prevent this “guesswork” pass the :exact option

Fractional.new(0.33333, exact: true).to_s  #=> "33333/100000"

It can render back out mixed numbers:

Fractional.new(1.45).to_s  #=> "29/20"
Fractional.new(1.45).to_s( mixed_number: true )  #=> "1 9/20"

Math and Comparisons

It will integrate nicely with Numerics:

a = Fractional.new("3/4")
puts a + 1.5   #=>  "9/4"

And you can compare it to other Numerics:

puts Fractional.new("3/4") > -2.3    #=> true

Rounding

Round a value to the nearest fraction:

Fractional.round_to_nearest_fraction("1100 1/7", "1/64")           #=> "1100 9/64"
Fractional.round_to_nearest_fraction(1100.142857142857143, "1/64") #=> 1100.140625

Note on Patches/Pull Requests

  • Fork the project.

  • Make your feature addition or bug fix.

  • Add tests for it. This is important so I don’t break it in a future version unintentionally.

  • Commit, do not mess with rakefile, version, or history. (if you want to have your own version, that is fine but bump version in a commit by itself I can ignore when I pull)

  • Send me a pull request. Bonus points for topic branches.

Special thanks

Thanks to Jannis Harder for his hardcore float to rational method I nicked from markmail.org/message/nqgrsmaixwbrvsno

Contributors

Joey Aghion github.com/joeyAghion

muff1nman github.com/muff1nman

Copyright © 2009-2013 Chris O’Sullivan. See LICENSE for details.