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

2 Answers

0 votes
using System;

internal class Program
{
	public static void Main(string[] args)
	{
		double d = 24278.0;

		if (d == Math.Floor(d)) {
			Console.WriteLine("The double variable contains an integer");
		}
		else {
			Console.WriteLine("The double variable contains a floating point");
		}
	}
}




/*
run:
  
The double variable contains an integer
  
*/

 



answered Mar 5, 2024 by avibootz
0 votes
using System;

class Program
{
    // -------------------------------------------------------------------------
    // Determines whether a double contains an integer (no fractional part).
    // Uses a small tolerance to safely handle floating‑point precision issues.
    // -------------------------------------------------------------------------
    static bool IsInteger(double value)
    {
        const double epsilon = 1e-12;

        // Math.Floor returns the largest integer <= value
        double floored = Math.Floor(value);

        // If the difference is extremely small, treat the number as an integer
        return Math.Abs(value - floored) < epsilon;
    }

    // -------------------------------------------------------------------------
    // Prints a descriptive message for the given double.
    // -------------------------------------------------------------------------
    static void PrintCheck(double value)
    {
        Console.WriteLine($"Checking value: {value:F15}");

        if (IsInteger(value))
            Console.WriteLine("Result: The value contains an integer.\n");
        else
            Console.WriteLine("Result: The value contains a floating-point number.\n");
    }

    // -------------------------------------------------------------------------
    // Entry point demonstrating several example values.
    // -------------------------------------------------------------------------
    static void Main()
    {
        // Example input values
        double a = 42.0;                 // integer-like
        double b = 42.00000000001;       // floating-point due to tiny fraction
        double c = 89.0000000000001;     // integer-like
        double d = -7.0;                 // negative integer-like
        double e = 3.14;                 // floating-point

        // Run checks
        PrintCheck(a);
        PrintCheck(b);
        PrintCheck(c);
        PrintCheck(d);
        PrintCheck(e);
    }
}



/*
run:

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

Checking value: 42.000000000010000
Result: The value contains a floating-point number.

Checking value: 89.000000000000100
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.

*/

 



answered Sep 10 by avibootz

Related questions

...