Skip to content

thechrisoshow/fractional

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

59 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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"

Convert to human-friendly fractions:

Fractional.new(-1.331, :to_human).to_s #=> "-1 1/3"

Consider the following example:

Fractional.new(1.339999).to_s => "67/50"
Fractional.new(1.339999).to_s(mixed_number: true) => "1 17/50"

This is not very human-friendly if we're talking about amounts in cooking recipes, especially when we need to convert from Kg to Pounds etc. Instead use:

Fractional.new(1.339999, to_human: true).to_s => "1 1/3"

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

Alex Nigomatulin github.com/GeNiuS69

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

About

Fractional is a Ruby library for parsing fractions

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages