How do I know if a BigDecimal failed to parse?

不打扰是莪最后的温柔 提交于 2019-12-07 00:57:33

问题


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?


回答1:


in simple case you can use RegExp

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



回答2:


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


来源:https://stackoverflow.com/questions/2789028/how-do-i-know-if-a-bigdecimal-failed-to-parse

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!