14,698,178 members
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.
`7`

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

:laugh:
Think of it!
http://msdn.microsoft.com/en-us/library/yht2cx7b.aspx

## Solution 1

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);
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:
```decimal d = (0.1M + 0.7M);
int v = (int)(d * 10);
Console.WriteLine(v);```
And it'll do what you expected.
Maciej Los 22-May-14 6:14am

Well explained!
Pratik Bhuva 22-May-14 9:44am

Thanks a lot sir.

## Solution 2

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));
```
Maciej Los 22-May-14 6:16am

5ed!
Pratik Bhuva 22-May-14 9:45am

Good solution you have added to OriginalGriff sir presentation.
Thanks a lot sir.

## Solution 3

Maciej Los 22-May-14 6:16am

5ed!
Pratik Bhuva 22-May-14 9:47am

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.