Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if a Float is equivalent to an integer value in Ruby

Say I have the following code:

x = 0.8 y = 1.0 

What's the best way of checking that y is equivalent to an Integer? At the moment I'm doing:

y.to_int == y 

which works, but I feel like there should be a better way.

like image 985
Skilldrick Avatar asked Feb 22 '11 19:02

Skilldrick


People also ask

How do you check if a float is an integer?

Check if float is integer: is_integer() float has is_integer() method that returns True if the value is an integer, and False otherwise.

Is float and integer equal?

Integers and floats are two different kinds of numerical data. An integer (more commonly called an int) is a number without a decimal point. A float is a floating-point number, which means it is a number that has a decimal place. Floats are used when more precision is needed.

What is the difference between a float and an integer in Ruby?

In other words, a float in a Ruby program is a number that contains a decimal point. Ruby will consider any number written without decimals as an integer (as in 138 ) and any number written with decimals as a float (as in 138.0 ).


1 Answers

You mod the value with 1, and check if the value equals 0.

if y % 1 == 0 
like image 98
Dogbert Avatar answered Sep 18 '22 15:09

Dogbert