如何确定是否一个小数/双为整数?
问题描述:
我如何判断一个小数或双值为整数?
How do I tell if a decimal or double value is an integer?
例如:
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
我想知道这种情况的原因是,这样我可以编程方式确定如果我想使用的输出的ToString(NO)
值或的ToString(N2)
。如果没有小数点值,那么我不想证明。
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.
答
有关浮点数, N%1 == 0
通常是检查是否有路任何过去的小数点。
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);
}
输出:
False
True