C#, DETERMINE *if* a double can become an int without any loss [duplicate]
Possible Duplicate:
How to determine if a decimal/double is an integer?
I have a unique situation in which all numbers must be saved as double
data type in my database, but only in certain conditions is the precision beyond the integer level valuable.开发者_如何学运维
At first, I tried to just use int
and then abstract to a new table when these unique fractional occurances would happen, but after doing that for weeks I can see now that it is excessively stupid and wasting my time.
I know that I can turn a double
into an int
. That is easy. I know how to translate it over. What I do not know is how to TEST for translating it over. I basically wish to come up with a short, easy way to say
Is this number really a double, or is it just an int?
If it is an int (and most of the time, it will be), then I will turn it into one and treat it as such. But due to the uniqueness of the requirements, I have to still save everything in the database as double
.
Any ideas? I know this is a newbie question, and I've googled around for several hours and am still left quite confused.
Cast it to an int
and see if it's still equal:
if ((int)val == val)
(int)val
will truncate any fractional portion.
Note that this may behave unexpectedly if the number is too large to retain complete precision in the double
.
double d = ...;
if(d == (int)d)
//is int
else
//is not int
Of course due to some precision issues, this may not work 100% times. You can use
double d = ...;
if(Math.Abs(d - (int)d) < Epsilon) //const double Epsilon = 0.000001;
//is int
else
//is not int
This similar post shows you how to determine if a double or decimal has decimal places or not. You can use this to determine what type it is and then store appropriately.
Accepted answer from that post:
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);
}
Output:
False
True
try this
double x = ......
if (Math.truncate(x) == x)
....... (is integer, unless its so big its outside the bounds)
精彩评论