Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a decimal to price format in Ruby

Hey I am using the ruby on rails framework and I have a price variable that is a decimal. Naturally values like $39.99 is fine but when the price is $39.90 my app shows the price as $39.9 How could I change that.

My view

%b price

= @product.price

like image 241
Alain Goldman Avatar asked Dec 12 '22 13:12

Alain Goldman


2 Answers

rails includes the number_to_currency(@product.price) helper. Little simpler and easier to remember.

like image 108
ctilley79 Avatar answered Dec 21 '22 15:12

ctilley79


The standard answer here is to use sprintf.

sprintf("$%2.2f", @product.price)

This will format your number with a leading dollar sign, then the number to two decimal places.

like image 34
Chris Heald Avatar answered Dec 21 '22 16:12

Chris Heald