user1742188
user1742188

Reputation: 5133

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?

Upvotes: 8

Views: 21418

Answers (2)

risa_risa
risa_risa

Reputation: 777

This post is old, so a little bit of an update for future readers. Rather than doing to_s which works, you can simply do string interpolation. It's also faster and more memory efficient.

x = 0.005
"With string interpolation: #{x}"  # => "With string interpolation: 0.005"
"Standard to_s method: " + x.to_s  # => "Standard to_s method: 0.005"

You can also do directly (tho, admittedly silly):

"string interpolation: #{0.005}"  # => "string interpolation: 0.005"

String interpolation is the way to go in Rails apps, mostly if you're pulling in ActiveRecord objects' various datatypes. It'll automatically .to_s it for you properly, and you simply need to call it as model.value instead of model.value.to_s.

Upvotes: 4

vidang
vidang

Reputation: 1771

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

Upvotes: 15

Related Questions