A. Singla A. Singla - 6 months ago 14
Ruby Question

Notice with variables and numbers with precision

pretty simple syntax question here, since I am new to rails. In my controller, I have two variables that I am trying to display in a notice after a redirect. They are piece.title and piece.price (piece is my model). The price is a decimal, and so I want to display it with two digits after the decimal (like

<%= number_with_precision piece.price, :precision => 2 %>

My current code is:

redirect_to pieces_path, notice: "Thanks for buying #{piece.title} for #{piece.price}."

This works, but how do I get the price to two decimal places? When I try to do the number with precision, I get syntax errors.



You can achieve it using this:

'%.2f' % 10 
#=> "10.00"

"Thanks for buying #{piece.title} for #{'%.2f' % price}."
#=> "Thanks for buying Coffee for 10.00."

Change your notice to this

class YourControllerName
  def my_method
    redirect_to pieces_path, notice: "Thanks for buying #{piece.title} for #{'%.2f' % piece.price}."