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?


在简单情况下,您可以使用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
链接地址: http://www.djcxy.com/p/45790.html

上一篇: 在核心文本中查找文本的边界矩形

下一篇: 如何知道BigDecimal是否无法解析?