'ruby how to keep decimals inside of a hash value with gets.to_i

I have

price_input = gets.strip.to_i

and I am trying to add it to an array of hashes. The adding to array works, but the .gets.strip.to_i removes any decimals. Is there a way to add it without it removing the decimals?

for further understanding, I have an existing array of hashes where ( price: [an integer] ) and I am adding these integers together with code later, so I need the .to_i because I can't add strings and integers



Solution 1:[1]

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

  1. Float#floor
  2. Float#ceil
  3. Float#round
  4. Float#rationalize

Solution 2:[2]

You can use to_f method. It converts String object to Float object. You also don't need strip method

"  0.2  ".to_f
# => 0.2

or in your case

price_input = gets.to_f

Keep in mind that when two integers interact, the result will always be an integer. If one number is an integer and the second is a float, the result will be a float

Solution 3:[3]

You can use below, this way if someone enters characters instead of a number, an error will be raised.

price_input = Float(gets)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Todd A. Jacobs
Solution 2 mechnicov
Solution 3 Manoj Saun