Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know if a BigDecimal failed to parse?

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?

like image 466
Michael Baldry Avatar asked May 07 '10 13:05

Michael Baldry


2 Answers

in simple case you can use RegExp

'123.4' =~ /^[+-]{0,1}\d+\.{0,1}\d*$/
=> 0
like image 196
andrykonchin Avatar answered Sep 20 '22 16:09

andrykonchin


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
like image 36
pithyless Avatar answered Sep 22 '22 16:09

pithyless