0

I noticed that the Math.Round() returns different values depending on the platform in which it is used.

I have already read the following discussion C# rounding differently depending on platform? , but I still can't explain what happens in this simple case

Here the code:

float c = (float)0.3;
int rounded= (int)Math.Round(c * 255);

If I build at x86 rounded is equal to 77, if I build at x64 rounded is equal to 76.

aSpagno
  • 141
  • 5
  • Why does it not explain it? That question shows you why the value can be different, [so](https://stackoverflow.com/q/588004/11683) it's slightly below 76.5 in one case and slightly over in another. – GSerg Sep 05 '19 at 11:19
  • 1
    The linked question **does** explain the behaviour, given that there is no overload of `Math.Round()` taking a `float`, but only `double`. There is an implicit cast from `float` to `double`, so you do call `Math.Round(double)` and the duplicate question applies. – René Vogt Sep 05 '19 at 11:23
  • 2
    The decimal value for 3 / 10 has no exact representation in binary. Just like 3 / 7 has no exact representation in decimal. The value must be approximated and that takes a dependency on the way the processor stores the value. Which is platform dependent, 32-bit code uses the legacy FPU that stores values with extended precision, 64-bit code uses modern SSE instructions that don't extend precision. Inevitably that can produce a different calculation result. Neither 76 nor 77 are wrong, use the Decimal type to avoid surprises. – Hans Passant Sep 05 '19 at 11:27

0 Answers0