Search code examples
rubybigdecimal

Ruby big decimal with 2 numbers after the decimal point


I this code:

require 'bigdecimal'
a = BigDecimal.new(1, 2)

While we can have those values:

a.to_s #=> "0.1E1"
a.to_f #=> 1.0

I would prefer to obtain this one: a.to_string # => "1.00"

Do you know if Ruby's BigDecimal is able to do this without having to create an additional #to_string method?

If not, what would be the best solution to have a big decimal number with always 2 numbers after the decimal point?


Solution

  • It can, but this is a kind of output format.

    sprintf( "%.02f", a)
    # => "1.00"
    

    You can define a method like this:

    class BigDecimal
      def to_string
        sprintf( "%.02f", self)
      end
    end
    
    a.to_string
    => "1.00"
    

    As suggested by @CarySwoveland, you also can write like this

    sprintf( "%.02f" % a)
    sprintf( "%.02f %.02f %.02f" % [a, b, c])