Zag zag..
Zag zag..

Reputation: 6231

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?

Upvotes: 3

Views: 1633

Answers (2)

pangpang
pangpang

Reputation: 8831

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

Upvotes: 2

Aaron Lasseigne
Aaron Lasseigne

Reputation: 205

If you don't need to define the scale you can use:

a.to_s('F') #=> "1.0"

Otherwise you'll need to use sprintf and specify the scale:

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

Upvotes: 0

Related Questions