I'm importing data from a csv, I need to cast some values to BigDecimal, and raise an error if they can't be parsed..
From testing, BigDecimal("invalid number") returns a BigDecimal of 0. This would be ok, but kind of messy, except a valid value is 0...
Float("invalid number") acts differently and throws an exception...
My current solution is:
class String
def to_bd
begin
Float(self)
rescue
raise "Unable to parse: #{self}"
end
BigDecimal(self)
end
end
Am I totally missing something?
in simple case you can use RegExp
'123.4' =~ /^[+-]{0,1}\d+\.{0,1}\d*$/
=> 0
I came across this inconsistent behavior today.
One approach:
def StrictDecimal(arg)
Float(arg)
BigDecimal(arg)
end
Or a more robust version:
def StrictDecimal(value)
if value.is_a?(Float)
fail ArgumentError, "innacurate float for StrictDecimal(): #{amount}"
end
Float(value)
BigDecimal(value)
rescue TypeError
fail ArgumentError, "invalid value for StrictDecimal(): #{amount}"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With