Search code examples
rubystringfloating-pointbigdecimal

Convert cents into dollar string in Ruby without use of BigDecimal


I want to convert from cents to dollars correctly in Ruby. I will never have to work with fractions of cents.

Is it possible to do this correctly (without floating point errors) without having to use BigDecimal?

E.g., cents to dollars

"99" => "0.99"
"324" => "3.24"

The following seems to work, but is it correct?

(cents.to_i/100.0).to_s

Update: I noticed the line above doesn't work if cents = "10287349283923497624861294712974892742837833".


Solution

  • Here's a one-line method that also simply uses string manipulation thereby completely bypassing the numeric issues:

    cents.rjust(3, "0").insert(-3, ".")