Question

I need to compare the integer part of two doubles for inequality and I'm currently doing this:

int iA = (int)dA;
int iB = (int)dB;

if( iA != iB )
{
    ...
}

but I wonder if there's a better approach than this.

Thanks.

If I used Math.Truncate() instead of a cast to int, would it still be accurate to compare the two resulting double values for equality?

About the hungarian notation comments:

I never use HN myself, not at least in the way most of people do. But this is one of these rare cases where the semantic of a variable directly relates to its type. I could have chosen another syntax like A_As_Integer and B_As_NonInteger but what would have been the difference then?

Was it helpful?

Solution

Use Math.Truncate() i.e.

if (Math.Truncate(x) == Math.Truncate(y))

[Edit] Realized that if you are comparing integer parts of doubles, casting to int values first runs the risk of overflows should your doubles be outside the range that could be represented as int.

Truncate returns either a Decimal or a double, avoiding this issue.

OTHER TIPS

Yes, that is best approach.

Assuming from your wording in you question you arent worried about rounding... just the integerr part itself.

ie. (int)4.1 will give the same result as (int)4.9

As Ovid stated, if you only need the variables for the comparison, then you will only need to cast the doubles in the comparison statement. I was looking only at the theory.

Personally, I try to avoid creating extra variables unless I need them.

if ( (int)dA != (int)dB ) {
    ...
}

As code evolves over time, having extra variables hanging around for no purpose leads to confusion. Of course, if you need those variables, that's another issue :)

Side note: you appear to be trying to hint at the data type via a simple Hungarian notation. May I recommend not doing that? If you must prefix information to your variables, try to prefix what the variable is for, rather than its type. If you do that, mistakes in code can be easier to see:

if ( (int)ageA != (int)idB ) {
    ...
}

In this case, without even knowing what the data is, seeing that you're trying to compare an 'age' with an 'id' is a good clue that something is wrong here.

I agree that Truncate is what you want.

Some helpful information from MSDN:

Truncate returns the number that remains after any fractional digits have been discarded.

It rounds to the nearest integer towards zero.

double floatNumber;

floatNumber = 32.7865;
// Displays 32      
Console.WriteLine(Math.Truncate(floatNumber));

floatNumber = -32.9012;
// Displays -32       
Console.WriteLine(Math.Truncate(floatNumber));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top