Sometimes when I try to print a Float in rails, I get an error like this:
TypeError at /delivery_requests/33/edit
no implicit conversion of Float into String
on the line:
= this_is_a_float
I know I can just add .to_s
to the float, but why is this not done by default?
Ruby provides the to_i and to_f methods to convert strings to numbers. to_i converts a string to an integer, and to_f converts a string to a float.
The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity. Syntax: number.to_f. Parameter: The function takes the integer which is to be converted to float. Return Value: The function returns the float value of the number.
Ruby has a well defined and often used typecasting infrastructure. to_s casts a value to a String , to_f casts a value to a Float , to_i casts a value to an Integer , etc. These are a helpful tool in our toolbox, but this too has limitations. First, there is no #to_* method that casts values into true or false .
Ruby allows part of a string to be modified through the use of the []= method. To use this method, simply pass through the string of characters to be replaced to the method and assign the new string.
This is because you're using a Float in place where a String is expected like the following example:
"Value = " + 1.2 # => no implicit conversion of Float into String
To fix this you must explicitly convert the Float into a String
"Value = " + 1.2.to_s # => Value = 1.2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With