Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a ruby BigDecimal to a 2-decimal place string?

Tags:

ruby

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?

like image 807
Saqib Ali Avatar asked Jul 22 '14 16:07

Saqib Ali


1 Answers

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).

like image 92
Neil Slater Avatar answered Oct 07 '22 13:10

Neil Slater