How can I convert a BigDecimal to a 2-decimal-place string?

The comments on the accepted answer contain important information.

It's been rightly pointed out that in older versions of Ruby, using "%.2f" % v will result in v being implicitly converted to a floating-point number, causing potential loss of precision/accuracy - e.g. "%.2f" % (10**24) == "999999999999999983222784.00"

You can convert BigDecimal to String accurately, even in older Rubies, by using .to_s("F"). This returns the number in fixed-point format, with a decimal point followed by zero or more decimal digits.

If you add "00" onto the end of the number (to ensure it has two or more decimal digits), then you can then strip it down using a regex like /.*\..{2}/ (any characters; a decimal point; then two more characters), so it only keeps the first two digits after the decimal point.

require 'bigdecimal'
w = BigDecimal("4.2")

 w.truncate(2).to_s("F")                       # => "4.2"
(w.truncate(2).to_s("F") + "00")               # => "4.200"
(w.truncate(2).to_s("F") + "00")[ /.*\..{2}/ ] # => "4.20"

How about combining BigDecimal#truncate and String#%? :

"%.2f" % BigDecimal("7.1762").truncate(2)
# => "7.17"
"%.2f" % BigDecimal("4.2").truncate(2)
# => "4.20"

Tags:

String

Ruby