Question

I have a variable that is a decimal and i want to determine if it "is an int"

  public bool IsanInt(decimal variable)

so if the variable passed in was 1, i want to return true
if it was 1.5, it would return false
.5 would be false
10 would be true

what is the best way to do this check?

Was it helpful?

Solution

Here you go:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(IsInt(3.0m)); // True
        Console.WriteLine(IsInt(3.1m)); // False
    }

    public static bool IsInt(decimal variable)
    {
        return ((variable % 1) == 0);
    }
}

Basically, that method is all you need. I just included the entire console program so that you can see the results.

EDIT:

So, after some brainstorming on the comments below, I found that it's incredibly difficult, if not impossible (I haven't found the way) to find if the value is decimal or "integer" if the decimal value being provided at its very high value. Decimal holds a higher value than even UInt64. When you run this line of code:

Console.WriteLine(Decimal.MaxValue - 0.5m);

Output:

79228162514264337593543950334

... you will see that it won't print the decimal value after the period. There is a maximum limitation that is forcing the truncation, so you'll never see that 0.5 being part of the that large value. My method can't fix that limitation. I'm not sure if there's anything that can do that within C# or .NET, but I'm all ears.

There's a good article on what you can and can't do with decimal... better than what MSDN provides in my opinion:

http://www.dotnetperls.com/decimal

OTHER TIPS

public bool IsInteger(decimal value)
{
    return value == Math.Round(value);
}

how about something like

return Math.Round(n) == n
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top