I want to convert a Ruby BigDecimal object to a nice, printable currency value. So I want it to print it to 2 decimal places. How can I do it?
As you can see, none of the following approaches worked:
irb(main):033:0> v = BigDecimal("7.1762")
=> #<BigDecimal:7fe97c1c9310,'0.71762E1',18(18)>
irb(main):034:0> v.to_s('2F')
=> "7.17 62"
irb(main):035:0> v.to_s('F')
=> "7.1762"
irb(main):036:0> v.to_s('%0.2F')
=> "0.71762E1"
irb(main):037:0> v.to_s('%0.2f')
=> "0.71762E1"
irb(main):038:0>
Which expression will just produce the string 7.17?
Without rounding, and without converting to a Float
, use BigDecimal#truncate
:
v = BigDecimal("7.1762")
v.truncate(2).to_s('F')
# => "7.17"
If you need to show trailing zeroes, it gets more complicated:
v = BigDecimal("4.1")
v.truncate.to_s + '.' + sprintf('%02d', (v.frac * 100).truncate)
# => "4.10"
which uses truncate
to convert to an Integer, always exact (and without rounding).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With