Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.