views:

47

answers:

1

Hi guys,

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?

A: 

in simple case you can use RegExp

'123.4' =~ /^[+-]{0,1}\d+\.{0,1}\d*$/
=> 0
aaz
that wasn't really my question, i can think of several ways to validate it, but why does BigDecimal not act like the other types when parsing strings
Michael Baldry
from documentation: "The initial value, as a String. Spaces are ignored, unrecognized characters terminate the value". So, its a feature
aaz