0

I expect result and result2 to be the same:

multiplying .1 x 10 should equal .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 + .1 when running following code snippt of C#.

public void DoubleAddition()
    {
        Double x = .1;
        Double result = 10 * x;
        Double result2 = x + x + x + x + x + x + x + x + x + x;

        Console.WriteLine("{0} - {1}", result, result2);
        Console.WriteLine("{0:R} - {1:R}", result, result2);
    }

But the output of Console.WriteLine("{0} - {1}", result, result2); is 1 - 1 And When is used round-trip formater e.g. Console.WriteLine("{0:R} - {1:R}", result, result2); then the result was 1 - 0.999999999999999989

Why is result2 not exactly is 1 when we display using round-trip formater? What is the value stored in memory when we declared Double d = 0.1?

Liam
  • 27,717
  • 28
  • 128
  • 190
Waqas Idrees
  • 1,443
  • 2
  • 17
  • 36
  • 5
    If you want the behaviour you're talking about: use `decimal`, not `double`. How IEEE floating points round is ... not that - and if you *expect* that, then that is an error of your expectation. If you replace `double` with `decimal` and `.1` with `.1M`, I strongly suspect it will all work as you expect. – Marc Gravell Nov 23 '17 at 13:11
  • http://www.exploringbinary.com/why-0-point-1-does-not-exist-in-floating-point/ – Janne Matikainen Nov 23 '17 at 13:11
  • 3
    [Let me just cart out the obligatory...](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) – Adam Houldsworth Nov 23 '17 at 13:17
  • I'd also read [When should I use double instead of decimal?](https://stackoverflow.com/questions/803225/when-should-i-use-double-instead-of-decimal) which goes into details from what Marc was saying – Liam Nov 23 '17 at 13:26

0 Answers0