可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
Possible Duplicate:
How to determine if a decimal/double is an integer?
I have a variable of type double and am wanting to check whether it is an integer.
At the moment I have
public bool CheckIfInteger(double number)
{
return number.ToString().Contains(".") == false;
}
Is there a better way?
UPDATE: Sorry I didn't realise the potential for confusion, by integer I meant the mathematical definiton of integer, that is the natural numbers together with the negatives of the non-zero natural numbers.
回答1:
return Math.Truncate(number) == number;
As mentioned in the comments, you might need to take account of the fact that a double
representation of your number might not be an exact integer. In that case you'll need to allow for some margin-of-error:
double diff = Math.Abs(Math.Truncate(number) - number);
return (diff < 0.0000001) || (diff > 0.9999999);
回答2:
If you want to check for an Integer, this will do it:
public bool IsInteger(double number)
{
return (number % 1 == 0);
}
If you additionally want to check if the number could be converted into an Int32:
public bool IsInt32(double number)
{
return (number % 1 == 0) && number >= Int32.MinValue && number <= Int32.MaxValue;
}
回答3:
The pitfall of working with string representations is the locale used and yoou have to take care of rounding issues. 0.999999999 can be considered to be integer 1 in most cases. Here is a small snippet taking into account rounding errors:
Math.Abs(number - Math.Round(number)) < EPSILON
where EPSILON is a double value that is small enough for your purpose 0.00001 for example
See also this for some more information: http://msdn.microsoft.com/en-us/library/system.double.epsilon.aspx
回答4:
Try:
public bool CheckIfInteger(double number)
{
return ((double) (int) number == number);
}
Or the prettier:
public bool CheckIfInteger(double number)
{
return (Math.Floor(number) == number);
}
回答5:
I'd use TryParse:
double value = 2.0;
int number;
bool result = Int32.TryParse(value.ToString(), out number);
回答6:
public static bool CheckIfInteger(double number)
{
return number - Math.Truncate(number) == 0;
}
回答7:
I think that a better question is: How can I tell if a double is close enough to an integer to be considered an integer for my purposes? Because otherwise, you are bound to run into ambiguities. So I'd recommend something like this:
return Math.Abs(someDouble - Math.Round(someDouble)) < TOLERANCE;
回答8:
I'm liking abatishchev's idea to use CurrentCulture.
return number.ToString().Contains(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator) == false;
Would this not solve the epsilon problem (which I didn't even consider initially)?
回答9:
I use the following string extension method which checks against a RegEx pattern
public static bool IsInteger(this string inputString)
{
Regex regexInteger = new Regex(@"^[-]?\d+$");
Match m = regexInteger.Match(inputString);
return m.Success;
}