Created
July 17, 2014 22:35
-
-
Save phaedryx/e6b1efe878d9584dfda1 to your computer and use it in GitHub Desktop.
convert a mixed number string to a decimal in Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def decimalize(string) | |
return 0.0 if string.nil? || string.empty? | |
string.gsub!(/[^\d\s\/]/, "") | |
fraction, numeral = string.split.reverse | |
fraction ||= '0/1' | |
numeral.to_i + Rational(fraction).to_f | |
end | |
# decimalize('1 1/2') => 1.5 | |
# decimalize('2 3/4 inches') => 2.75 | |
# decimalize('3 11/8') => 4.375 | |
# decimalize('') => 0.0 | |
# decimalize(nil) => 0.0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment