Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#, DETERMINE *if* a double can become an int without any loss [duplicate]

Tags:

c#

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.

like image 773
Derek Avatar asked Aug 12 '11 13:08

Derek


3 Answers

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.

like image 151
SLaks Avatar answered Sep 28 '22 01:09

SLaks


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
like image 33
Armen Tsirunyan Avatar answered Sep 28 '22 01:09

Armen Tsirunyan


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
like image 42
Chris Snowden Avatar answered Sep 28 '22 02:09

Chris Snowden