How do I know if BigDecimal failed?

I import data from csv, I need to transfer some values ​​to BigDecimal and raise an error if they cannot be analyzed.

From testing, BigDecimal ("invalid number") returns BigDecimal of 0. This would be normal, but sort of randomly, except for a valid value of 0 ...

Float ("invalid number") acts differently and throws an exception ...

My current solution:

class String def to_bd begin Float(self) rescue raise "Unable to parse: #{self}" end BigDecimal(self) end end 

Am I missing something at all?

+7
ruby bigdecimal
source share
2 answers

in the simple case you can use RegExp

 '123.4' =~ /^[+-]{0,1}\d+\.{0,1}\d*$/ => 0 
+2
source share

Today I came across this inconsistent behavior.

One approach:

 def StrictDecimal(arg) Float(arg) BigDecimal(arg) end 

Or a more reliable 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 
+2
source share

All Articles