How to check if a number has a decimal number?

I want to specifically check if this number contains ".5"

I deal only with integers and halves (0.5, 1, 1.5, etc.).

+11
source share
5 answers

% should work

 variable % 1 != 0 

Check out this RubyFiddle .

Here is a javascript fiddle too.

+27
source

Always use BigDecimal to check the fractional part of a number to avoid floating point errors :

 require 'bigdecimal' BigDecimal.new(number).frac == BigDecimal("0.5") 

For example:

 BigDecimal.new("0.5").frac == BigDecimal("0.5") # => true BigDecimal.new("1.0").frac == BigDecimal("0.5") # => false 

And a more general solution to see if an integer is:

 BigDecimal.new("1.000000000000000000000000000000000000000001").frac.zero? # => false 
+9
source

myValue == myValue.floor

or if you really want to check specifically for 0.5, 1.5, etc.

myValue - myValue.floor == 0.5

+7
source
 (2.50).to_s.include?('.5') #=> true (2).to_s.include?('.5') #=> false 
+1
source

Try

 n = 1.5 # => 1.5 n - Integer(n) == 0.5 # => true 
-one
source

All Articles