user2873003
user2873003

Reputation: 356

Ruby round answer to 2nd decimal place?

Learning ruby and want to make a simple string where:

puts "A Honda Fit cost $#{3.98 * 10.6} to fill up."

The answer I'm getting is $42.1879999999995; would like the answer to round to two decimal places.

Thanks for the help.

Upvotes: 0

Views: 120

Answers (2)

enrico.bacis
enrico.bacis

Reputation: 31484

You don't need to change the model of the data, you can just change the view, printing two decimals:

puts "A Honda Fit cost $%.2f to fill up." % (3.98 * 10.6)

Upvotes: 3

xlembouras
xlembouras

Reputation: 8295

You can also use the Float#round method

puts "A Honda Fit cost $#{(3.98 * 10.6).round(2)} to fill up."
#=> A Honda Fit cost $42.19 to fill up.

Upvotes: 4

Related Questions