rubyexceptioncasting

How to raise an error when converting a non-numeric string to float


I'm prompting the user to enter a float. Afterward I try to convert the received string to float. In case the user has entered an invalid value (string with special characters, etc.), which can't be converted to float, I expected an exception to be thrown.

But that isn't the case:

result = "XYZ§&()123!".to_f
#=> 0.0

Instead 0.0 is returned!

Actual I intended to put the conversion into a begin-rescue.

In case the user has entered an invalid value, it goes into the rescue-branch. An error-message is displayed and then the script terminated. At least, that was my intention.

How can I handle the situation, when the user entered an invalid value?

0.0 is a perfectly valid value, which can be entered by the user as well. How can I differentiate if it comes from .to_f as a result of a failed cast or was actually entered by the user? The both possibilities have to be handled differently.

The Ruby behavior differs from Python, where an exception is thrown.

float("XYZ$&()123!")
# Traceback (most recent call last):
#  File "<python-input-0>", line 1, in <module>
#    float("XYZ$&()123!")
#    ~~~~~^^^^^^^^^^^^^^^
# ValueError: could not convert string to float: 'XYZ$&()123!'
 

Solution

  • You can use the Float() method when you want to raise an exception when the string contains anything other that the string representation of a float.

    Float("XYZ$&()123!")
    # raises 'Kernel#Float': invalid value for Float(): "XYZ$&()123!" (ArgumentError)
    
    Float("123")
    #=> 123.0