Round to two decimal place

T

Tom Mac

Hi
I have a variable say @price. It is either blank or has a value. If
it is blank I have to show it like $ 0.00 . So I wrote helper like

@price.blank? ? '$'+'0.00' : '$'(e-mail address removed)_s


But the problem if @price has value 400.00 , after doing
@price.to_s it changes to 400.0 What I want is exactly 400.00 .And if
I remove to_s above it will throw an error
can't convert BigDecimal into String

Please help
Thanks
Tom
 
J

Josh Cheek

[Note: parts of this message were removed to make it a legal post.]

Hi
I have a variable say @price. It is either blank or has a value. If
it is blank I have to show it like $ 0.00 . So I wrote helper like

@price.blank? ? '$'+'0.00' : '$'(e-mail address removed)_s


But the problem if @price has value 400.00 , after doing
@price.to_s it changes to 400.0 What I want is exactly 400.00 .And if
I remove to_s above it will throw an error
can't convert BigDecimal into String

Please help
Thanks
Tom
Based on your use of the word "helper" I assume you're using Rails (this is
not a Rails forum), if that is so, try
http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_to_currency



Otherwise, check out sprintf

require 'bigdecimal'
@price = BigDecimal.new "400.00"
sprintf( "$%.02f" , @price ) # => "$400.00"

For more details on how to create a format string, the docs for sprintf are
pretty good http://ruby-doc.org/ruby-1.9/classes/Kernel.html#M002627
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top