How can I see if the string is numeric?

落花浮王杯 提交于 2020-01-06 03:54:30

问题


I have the string "08" and I like to know if this string is numeric. How can I do it in Rails 3.1?


回答1:


Another way to do this is to leave it up to ruby to determine it:

begin
    Float(string)
    # String is numeric
rescue ArgumentError, TypeError
    # String is not numeric
end



回答2:


You can use a regular expression:

str = "08"
if str =~ /^-?(\d+(\.\d+)?|\.\d+)$/
  # string is numeric
else
  # string is not
end



回答3:


If you are wanting to validate user input it would be just as simple to only allow them to input numbers with something like validates_format_of :string, :with => /[0-9]/.



来源:https://stackoverflow.com/questions/9469587/how-can-i-see-if-the-string-is-numeric

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