-1

This is the simplest form of my problem and I wonder how this happen?

Console.WriteLine(3.12 * 3.14);

What it do to give this result?

9.796800000000001

It makes me problem for my general code and program. How to avoid this and give me the exact desired output?

AhmadReza
  • 21
  • 1
  • Thanks, I wonder why I didn't know about this :( sorry if my question is so amateurish. but I can't find the answer how to avoid this problem in the link. – AhmadReza Sep 19 '20 at 10:23

1 Answers1

1

You can use float

        var x = (float)3.12;
        // or var x = 3.12f
        var y = (float)3.14;
        var result = x * y;
        Console.WriteLine(result);
Mustafa Arslan
  • 774
  • 5
  • 13
  • Thanks for the answer. why (double) doesn't work. and another amateurish question, why `float pi = 3.14;` gets an error and it needs `(float)3.14`? – AhmadReza Sep 19 '20 at 10:27
  • Its about hardware(CPU) calculations for 64bit floating-points. Compiler allocates 64bit memory for `3.14` and `float` is 32bit. `(float)` casting a 64bit variable(`double`) to 32bit variable(`float`). `3.14f` creates directly 32bit. – Mustafa Arslan Sep 19 '20 at 10:30
  • 1
    Of course you can use `decimal` too. Rounding errors occur on 64bit. Not on 32bit and 128bit. `decimal` provides more sensitivity but need more CPU cycles. – Mustafa Arslan Sep 19 '20 at 10:50
  • Yes, I found this useful for anyone who have the same problem as me too : http://www.net-informations.com/q/faq/float.html I see `float` could make problem in rounding somewhere too. Thanks for all the answers. – AhmadReza Sep 19 '20 at 11:00