Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Float to a String in Ruby

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?

like image 659
user1742188 Avatar asked Jan 14 '14 05:01

user1742188


People also ask

How do I convert a number to a string in Ruby?

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.

What is TO_F in Ruby?

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.

How do you write cast in Ruby?

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 .

How do you replace a string in Ruby?

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.


1 Answers

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
like image 96
vidang Avatar answered Oct 24 '22 04:10

vidang