简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM