Jim Geurts Jim Geurts - 1 year ago 132
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


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
. If there is no decimal point value, then I don't want to show that.

Answer Source

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);


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download