简体   繁体   中英

In C#, what is the best way to determine if a decimal “is an int”?

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?

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

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

怎么样

return Math.Round(n) == n

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM