Click here to Skip to main content
15,878,959 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
C#
Console.WriteLine((int) ((0.1 + 0.7) * 10));

This gives following Output when i run this on my machine.
C#
7


It will be helpful to me if anybody explain me why i am getting 7?
Posted
Updated 21-May-14 23:47pm
v2
Comments
Maciej Los 22-May-14 5:56am    
:laugh:
Think of it!
http://msdn.microsoft.com/en-us/library/yht2cx7b.aspx

It's fairly simple, though it may be difficult to understand.
Try doing it like this:
C#
double d = (0.1 + 0.7);
int v = (int)(d * 10);
Console.WriteLine(v);
And look at the value of d in the debugger.
It's not what you expect - 0.8 - but 7.9999999999999999 instead.

Why? Because base 10 and base 2 do not "play nice" all the time, and a fractional value that is "solid" in base 10 (like 0.1 + 0.7) is not so solid in base 2.

Try using decimal values:
C#
decimal d = (0.1M + 0.7M);
int v = (int)(d * 10);
Console.WriteLine(v);
And it'll do what you expected.
 
Share this answer
 
Comments
Maciej Los 22-May-14 6:14am    
Well explained!
Pratik Bhuva 22-May-14 9:44am    
Thanks For your valuable time.
its very helpful.
Thanks a lot sir.
In this case 0.1 and 0.7 are by default double type.
As per OriginalGriff sir presentation so both of addition value will expect 7.9999999999999999 instead of 0.8.
For the solution I am really impressed.
And one more solution can possible if we will use decimal type also
Where decimal numbers are exactly representable in binary floating point 0.1, For values which are more artefacts of nature which can't really be measured exactly anyway, float/double are more appropriate. For example, scientific data would usually be represented in this form. Here, the original values won't be "decimally accurate" to start with, so it's not important for the expected results to maintain the "decimal accuracy".

Solution:
Console.WriteLine((int)(((decimal)0.1 +(decimal) 0.7) * 10));
 
Share this answer
 
Comments
Maciej Los 22-May-14 6:16am    
5ed!
Pratik Bhuva 22-May-14 9:45am    
Thanks For your valuable time.
Good solution you have added to OriginalGriff sir presentation.
Thanks a lot sir.
 
Share this answer
 
Comments
Maciej Los 22-May-14 6:16am    
5ed!
Pratik Bhuva 22-May-14 9:47am    
Thanks For sharing this link.
Now i am going read this all to know how it works.
After IDE age what we are looking is just Abstraction of this underlying & really valuable processing.

Thanks a lot sir.

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