1

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!'
 
1

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

... not to forget hexadecimal floating point notation (0x...) which uses p instead of e. It might come as another surprise that Float("-0xc.90fep-2") parses perfectly fine ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.