2014-09-26 80 views
1

我認爲這樣會比較容易找到,但我很驚訝它不是。如何確定字符串是否爲數字?

如何在地球上測試字符串是否是模型外的數字(包括小數)?

例如

is_number("1") # true 
is_number("1.234") # true 
is_number("-1.45") # true 
is_number("1.23aw") #false 

在PHP中,有is_numeric,但我似乎無法找到紅寶石(或Rails)的等價物。

到目前爲止,我已經閱讀了以下的答案,並沒有得到任何接近:

+0

的可能重複的[與導軌驗證數3](http://stackoverflow.com/questions/22924153/validate-number-with-rails-3) – 2014-09-26 14:16:14

+1

@JustinWood溶液存在不適用於絃樂器 – FloatingRock 2014-09-26 14:18:09

+0

讓看問題的根源。你如何得到這個可能或不可能是「數字」的字符串? – 2014-09-26 14:22:02

回答

6

你可以從你借的想法Rails使用NumericalityValidator驗證號碼,它使用Kernel.Float方法:

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 

它也處理的跡象,十六進制數字,並寫入科學記數法表示:

numeric?('-10') # => true 
numeric?('0xFF') # => true 
numeric?('1.2e6') # => true 
+0

所以我必須定義這種方法,對吧? (即它不是內置的) – FloatingRock 2014-09-26 14:29:52

+1

是的,沒有用於此目的的內置或庫函數。 – toro2k 2014-09-26 14:37:11

4

你可以使用正則表達式。

!!("1" =~ /\A[-+]?[0-9]+(\.[0-9]+)?\z/) # true 
!!("1.234" =~ /\A[-+]?[0-9]+(\.[0-9]+)?\z/) # true 
!!("-1.45" =~ /\A[-+]?[0-9]+(\.[0-9]+)?\z/) # true 
!!("1.23aw" =~ /\A[-+]?[0-9]+(\.[0-9]+)?\z/) # false 

您可以使用它像這樣或作出的方法模塊中或在String類中添加此

class String 
    def is_number? 
    !!(self =~ /\A[-+]?[0-9]+(\.[0-9]+)?\z/) 
    end 
end 

您可以使用該網站來測試你的表達:Rubular: a Ruby regular expression editor and tester

我如果需要,可以解釋更多的表達。

希望這會有所幫助。

+0

這個失敗的值大於10,例如'0xdeadbeef' – 2014-09-26 15:42:30

+2

爲什麼要downvote? OP沒有表明他想要測試一個特定的基數或10以外的值。並且可以更改正則表達式,所以答案仍然有效。 – 2014-09-26 17:46:45

+0

@FredPerrin我收到你的回覆 – FloatingRock 2014-09-26 17:48:29

相關問題