Jim Geurts Jim Geurts - 16 days ago 5
C# Question

How to determine if a decimal/double is an integer?

How do I tell if a decimal or double value is an integer?

For example:

decimal d = 5.0; // Would be true
decimal f = 5.5; // Would be false


or

double d = 5.0; // Would be true
double f = 5.5; // Would be false


The reason I would like to know this is so that I can determine programmatically if I want to output the value using
.ToString("N0")
or
.ToString("N2")
. If there is no decimal point value, then I don't want to show that.

Answer

For floating point numbers, n % 1 == 0 is typically the way to check if there is anything past the decimal point.

    public static void Main (string[] args)
    {
        decimal d = 3.1M;
        Console.WriteLine((d % 1) == 0);
        d = 3.0M;
        Console.WriteLine((d % 1) == 0);
    }

Output:

False
True
Comments