I know this has been discussed time and time again, but I can’t seem to get even the most simple example of a one-step division of doubles to result in the expected, unrounded outcome in C# – so I’m wondering if perhaps there’s i.e. some compiler flag or something else strange I’m not thinking of. Consider this example:
double v1 = 0.7;
double v2 = 0.025;
double result = v1 / v2;
When I break after the last line and examine it in the VS debugger, the value of “result” is 27.999999999999996. I’m aware that I can resolve it by changing to “decimal,” but that’s not possible in the case of the surrounding program. Is it not strange that two low-precision doubles like this can’t divide to the correct value of 28? Is the only solution really to Math.Round the result?
No, not really. Neither 0.7 nor 0.025 can be exactly represented in the
doubletype. The exact values involved are:Now are you surprised that the division doesn’t give exactly 28? Garbage in, garbage out…
As you say, the right result to represent decimal numbers exactly is to use
decimal. If the rest of your program is using the wrong type, that just means you need to work out which is higher: the cost of getting the wrong answer, or the cost of changing the whole program.