You could borrow the idea from the NumericalityValidator
Rails uses to validate numbers, it uses the Kernel.Float
method:
def numeric?(string)
# `!!` converts parsed number to `true`
!!Kernel.Float(string)
rescue TypeError, ArgumentError
false
end
numeric?('1') # => true
numeric?('1.2') # => true
numeric?('.1') # => true
numeric?('a') # => false
It also handles signs, hex numbers, and numbers written in scientific notation:
numeric?('-10') # => true
numeric?('0xFF') # => true
numeric?('1.2e6') # => true
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…