Storing Input Strings in BigDecimal
Integers are not Floats, and Floats are a bad way to handle financial representations. There are gems for handling money that abstract away the various issues with floating point math, but if you're just looking for something simple:
require "bigdecimal"
print "Enter a price: "
price_input = BigDecimal(gets)
puts "You entered $#{price_input.to_f.round 2}"
You don't even have to chomp or strip your input, as BigDecimal will handle that for you. However, please keep in mind that even though BigDecimal or Real will correctly handle fractional cents, anything involving fractions of a penny can lead to rounding errors of one sort or another when you convert back to a Float with a precision of 2, so you'll need to decide what to do about rounding regardless of your internal representation.
See Also
- Float#floor
- Float#ceil
- Float#round
- Float#rationalize