How to check if number has a decimal?

myValue == myValue.floor

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

myValue - myValue.floor == 0.5


% should work

variable % 1 != 0

Check this RubyFiddle.

Here is a JavaScript fiddle, too.


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 a number is whole:

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

Tags:

Ruby