vectran vectran - 2 months ago 8
Ruby Question

Convert BigDecimal String to currency

I have a pure string value which was obtained from a API call and is stored in a database as a string:

#<BigDecimal:7fabd9ba9618,'0.4173E2',18(18)>


This needs to be converted into a currency value somehow.

I would expect something like this to work, but it just returns as zero.

v = BigDecimal.new("#<BigDecimal:7fabd9ba9618,'0.4173E2',18(18)>")
return v.to_s('F')


Any ideas?

Answer

First: why are those BigDecimal's stored in BigDecimal#inspect representation in the DB? This is wrong and bad and should be fixed.

While the format seems to be documented in the ruby API it is probably not guaranteed to be persistent across versions.

I'd use a regexp to parse out the relevant part, just to be sure that I read the right things and get a proper error when the format does not match:

match = big_decimal_as_string.match(/#<BigDecimal:[a-f0-9]+,'([0-9E\.]+)',\d+\(\d+\)>/)
if match
  BigDecimal.new(match[1])
else
  raise "Could not parse #{big_decimal_as_string}"
end