Ruby-on-rails 如何检查值是否为数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2095493/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:09:57  来源:igfitidea点击:

How can I check if a value is a number?

ruby-on-railsruby

提问by user211662

I want to simply check if a returned value from a form text field is a number i.e.: 12 , 12.5 or 12.75. Is there a simple way to check this, especially if the value is pulled as a param?

我只想检查表单文本字段的返回值是否是数字,即: 12 、 12.5 或 12.75 。有没有一种简单的方法来检查这一点,尤其是当值被拉为 a 时param

采纳答案by cwninja

Just regexp it, it's trivial, and not worth thinking about beyond that:

只需对其进行正则表达式,这很简单,除此之外不值得考虑:

v =~ /\A[-+]?[0-9]*\.?[0-9]+\Z/

(Fixed as per Justin's comment)

(根据贾斯汀的评论修复)

回答by Peter

You can use

您可以使用

12.is_a? Numeric

(Numericwill work for integers and floats.)

Numeric适用于整数和浮点数。)

If it arrives as a string that might contain a representation of a valid number, you could use

如果它作为可能包含有效数字表示的字符串到达​​,则可以使用

class String
  def valid_float?
    true if Float self rescue false
  end
end

and then '12'.valid_float?will return true if you can convert the string to a valid float (e.g. with to_f).

然后'12'.valid_float?将返回 true 如果您可以将字符串转换为有效的浮点数(例如 with to_f)。

回答by daesu

I usually just use Integer and Float these days.

这些天我通常只使用 Integer 和 Float 。

1.9.2p320 :001 > foo = "343"
 => "343"
1.9.2p320 :003 > goo = "fg5"
 => "fg5"

1.9.2p320 :002 > Integer(foo) rescue nil
 => 343
1.9.2p320 :004 > Integer(goo) rescue nil
 => nil

1.9.2p320 :005 > Float(foo) rescue nil
 => 343.0
1.9.2p320 :006 > Float(goo) rescue nil
 => nil

回答by ryanprayogo

You can add a:

您可以添加一个:

validates_numericality_of :the_field

in your model.

在你的模型中。

See: http://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002172

请参阅:http: //api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html#M002172

回答by Evan Ross

Just convert string twice:

只需将字符串转换两次:

num = '12'
num == num.to_i.to_s 
#=> true 

num = '3re'
num == num.to_i.to_s 
#=> false

回答by Brian Armstrong

irb(main):005:0> 1.1.is_a? Numeric
=> true
irb(main):006:0> 1.is_a? Numeric
=> true
irb(main):007:0> 'asd'.is_a? Numeric
=> false

回答by installero

I would suggest this one

我会推荐这个

def is_number?
  self.to_f == self
end

> 15.is_number?
=> true
> 15.0.is_number?
=> true
> 'Not a number'.is_number?
=> false
> (0/0.0).is_number?
=> false

回答by Adrian Teh

String values always convert to 0 with .to_i

字符串值总是使用 .to_i 转换为 0

[14] pry(main)> 'Apple'.to_i > 0
=> false

[15] pry(main)> '101'.to_i > 0
=> true