Click here to Skip to main content
15,885,366 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
The next code doesn't show the message "Equal" when x is equal 1:
C#
for (double x = 0; x <= Convert.ToDouble(1); x += 0.1)
{
    MessageBox.Show(x.ToString());
    if (x == Convert.ToDouble(1)) MessageBox.Show("Equal");
}

How to fix?
Posted
Updated 12-Oct-14 2:20am
v2
Comments
[no name] 12-Oct-14 8:26am    
http://msdn.microsoft.com/en-us/library/ya2zha7s(v=vs.110).aspx
Afzaal Ahmad Zeeshan 12-Oct-14 8:33am    
Exactly, in that case both the operands are of double type. The precision causes the types to be not equal to an integral value.

For more, see my answer and the fiddle that evaluates your values.
[no name] 12-Oct-14 8:38am    
No thanks. I would prefer code that works. Nice try though.
Afzaal Ahmad Zeeshan 12-Oct-14 8:47am    
I am sorry, the last paragraph was for the OP, not for you.

However, that code works try the fiddle, and if you meant you wanted a .NET way of doing it, then yeah! You're right. :-)
Afzaal Ahmad Zeeshan 12-Oct-14 8:51am    
Sorry, I read the second solution after I posted the comment!

 
Share this answer
 
After you read the article Carlo posted - and understood the floating point problem...
Use Decimal[^]...
C#
for ( decimal x = 0; x <= ( decimal )1; x += ( decimal )0.1 )
{
    Debug.WriteLine ( x.ToString ( ) );
    if ( x == ( decimal )1 )
        Debug.WriteLine ( "Equal" );
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900