How to check whether a floating-point variable is an integer (has no fractional part) in Ruby

1 Answer

0 votes
# -----------------------------------------------------------------------------
# Determines whether a floating‑point number (Float) is an integer.
# Uses a small tolerance to safely handle floating‑point precision issues.
# Ruby's Float behaves like a double‑precision floating‑point value.
# -----------------------------------------------------------------------------
def integer?(value)
  epsilon = 1e-12

  # floor returns the largest integer <= value
  floored = value.floor

  # If the absolute difference is extremely small, treat the number as integer
  (value - floored).abs < epsilon
end

# -----------------------------------------------------------------------------
# Prints a descriptive message for the given floating‑point value.
# -----------------------------------------------------------------------------
def print_check(value)
  puts "Checking value: #{format('%.15f', value)}"

  if integer?(value)
    puts "Result: The value contains an integer.\n\n"
  else
    puts "Result: The value contains a floating‑point number.\n\n"
  end
end

# -----------------------------------------------------------------------------
# Entry point demonstrating several example values.
# -----------------------------------------------------------------------------
def main
  # Example input values (Ruby Float behaves like a double)
  a = 42.0                 # integer-like
  b = 42.00000000001       # floating-point due to tiny fraction
  c = 89.0000000000001     # integer-like
  d = -7.0                 # negative integer-like
  e = 3.14                 # floating-point

  # Run checks
  print_check(a)
  print_check(b)
  print_check(c)
  print_check(d)
  print_check(e)
end

main


=begin
run:

Checking value: 42.000000000000000
Result: The value contains an integer.

Checking value: 42.000000000009997
Result: The value contains a floating‑point number.

Checking value: 89.000000000000099
Result: The value contains an integer.

Checking value: -7.000000000000000
Result: The value contains an integer.

Checking value: 3.140000000000000
Result: The value contains a floating‑point number.

=end

 



answered Sep 10 by avibootz

Related questions

...