Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby check if even number, float

Tags:

ruby

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

So how can i check if the number is even?

like image 778
John Smith Avatar asked Aug 10 '13 15:08

John Smith


People also ask

How do you check if a number is even in Ruby?

The even? function in Ruby returns a boolean value. It returns true if the number is even, else it returns false. Syntax: number.

Is a float Ruby?

A floating-point number or a float represents a real number. Real numbers can be either a rational or an irrational number; numbers that contain a fractional part, such as 9.0 or -116.42 . In other words, a float in a Ruby program is a number that contains a decimal point.

How do you check if a number is an integer in Ruby?

How do you check if a value is an integer? The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you find odd numbers in Ruby?

function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number. odd?


1 Answers

Make it an Integer then:

a = 4.0
a.to_i == a && a.to_i.even?  #=> true
like image 187
Yu Hao Avatar answered Oct 09 '22 06:10

Yu Hao