Skip to content

Instantly share code, notes, and snippets.

@phaedryx
Created July 17, 2014 22:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phaedryx/e6b1efe878d9584dfda1 to your computer and use it in GitHub Desktop.
Save phaedryx/e6b1efe878d9584dfda1 to your computer and use it in GitHub Desktop.
convert a mixed number string to a decimal in Ruby
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