简体   繁体   中英

Handling BigDecimal trailing zero's Ruby

I am using BigDecimal values in my app as there are calculations to be made for goods in a shopping cart, I read that BigDecimal is preferred for this, compared to say integers or floats?

There is one scenario which I would like to address. When I have this for example

amount = BigDecimal.new("28.99")
amount      #=> #<BigDecimal:51d3120,'0.2899E2',18(18)>
amount.to_s #=> "28.99"
amount.to_f #=> 28.99

Which so far is expected behavior but when I do the following

amount = BigDecimal.new("28.00") || amount = BigDecimal.new("28") 
amount.to_s #=> "28.0"
amount.to_f #=> 28.0

Is this intended behavior ? In my db I have set the scale and precision

t.decimal :price, precision: 30, scale: 2

When I have a value of 28.00 saved in the database I would like to show in my view 28.00 and not 28.0

Update

Just come across this post on SO How to convert a ruby BigDecimal to a 2-decimal place string? the solution being

v = BigDecimal("28.00")
v.truncate.to_s + '.' + sprintf('%02d', (v.frac * 100).truncate)

I guess this is the only way to handle it ?

sprintf("%2.f", v) should work. The options for sprintf can be found at

http://ruby-doc.org/core-2.3.0/Kernel.html#method-i-sprintf

Also, if you're using Rails, the number_with_precision helper is probably easier to use - you can find the documentation at http://api.rubyonrails.org/classes/ActionView/Helpers/NumberHelper.html#method-i-number_with_precision

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM