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

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

It will be helpful to me if anybody explain me why i am getting 7?
Updated 22-May-14 0:47am
Maciej Los 22-May-14 5:56am
Think of it!

It's fairly simple, though it may be difficult to understand.
Try doing it like this:
double d = (0.1 + 0.7);
int v = (int)(d * 10);
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:
decimal d = (0.1M + 0.7M);
int v = (int)(d * 10);
And it'll do what you expected.
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".

Console.WriteLine((int)(((decimal)0.1 +(decimal) 0.7) * 10));
Maciej Los 22-May-14 6:16am
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.
Maciej Los 22-May-14 6:16am
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

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