Ruby check if even number, float

前端 未结 3 1258
长发绾君心
长发绾君心 2021-02-19 18:16

I want to check if the number is even! I tried the following:

a = 4.0
a.is_a? Integer

=> false

a.even?

=> undefined method for Float

S

相关标签:
3条回答
  • 2021-02-19 18:34

    If you are unsure if your variable has anything after the decimal and would like to check before converting to integer to check odd/even, you could do something like this:

    a = 4.6
    b = 4.0
    
    puts a%1==0 && a.to_i.even? #=> false
    puts b%1==0 && a.to_i.even? #=> true
    

    Additionally, if you want to create an even? method for the Float class:

    class Float
      def even?
        self%1==0 && self.to_i.even?
      end
    end
    
    a = 4.6
    b = 4.0
    
    a.even? #=> false
    b.even? #=> true
    
    0 讨论(0)
  • 2021-02-19 18:35

    Just keep in mind how numbers are converted:

    (4.0).to_i # same as Integer(4.0)
    => 4
    (4.5).to_i
    => 4
    (4.9).to_i
    => 4
    

    Using round may be safer:

    (4.0).round
    => 4
    (4.5).round
    => 5
    (4.9).round
    => 5
    

    Then of course you can call even as @Yu Hao wrote:

    (4.5).round.even?
    => false
    

    You can also easily observe known floats 'feature':

    (4.499999999999999).round.even?
    => true
    (4.4999999999999999).round.even?
    => false
    
    0 讨论(0)
  • 2021-02-19 18:52

    Make it an Integer then:

    a = 4.0
    a.to_i == a && a.to_i.even?  #=> true
    
    0 讨论(0)
提交回复
热议问题