1

I have this code to round some value. I am using Math.Round() for the same.

double h = 128.015999031067; double d = Math.Round(h, 3) * 1000;

result is 128015.99999999999 if I write it to console it gives me 128016. I want the value to be 128016

Am I missing any type conversions? Or there is some other way of doing this?

Shirish11
  • 1,587
  • 5
  • 17
  • 39
  • 3
    But it is working as you expected - https://dotnetfiddle.net/szBxpQ - the output is `128016` – Felipe Oriani Jul 17 '18 at 11:38
  • Very carefully consider your numerics here, IEEE 754 `float` and `double` cannot accurately represent all numbers. Verify that these types will work correctly for the calculations you wish to make. – Mgetz Jul 17 '18 at 11:38
  • 1
    See https://stackoverflow.com/questions/24859628/c-sharp-float-and-double-bug/24859646#24859646 – Magnus Jul 17 '18 at 11:39
  • @FelipeOriani let me know if it prints Match https://dotnetfiddle.net/kQB4Xk – Shirish11 Jul 17 '18 at 12:02
  • 1
    You can consider using `decimal` https://dotnetfiddle.net/FCcepy – Felipe Oriani Jul 17 '18 at 12:07
  • @FelipeOriani I know that's one solutions. Just trying to avoid type conversion changes in my code. Thanks – Shirish11 Jul 17 '18 at 12:12

2 Answers2

8

128.016 cannot be represented exactly in binary. There is no way that you will get 128016 by multiplying with 1000.

There are multiple ways around this:

  • Do nothing. It is already printed correctly. (Unless you want to perform further calculations.)
  • The "obvious" solution would be to simply round again.
  • The "simplest" solution would be to multiply first, then round.
  • The most "correct" solution would be, if you need exact values, you should use an exact type; there are many implementations of bignum, rational, decimal, and precise arithmetic available via NuGet, also consider using decimal.
Jörg W Mittag
  • 363,080
  • 75
  • 446
  • 653
  • I want to perform a value match of the rounded value which it fails. And I am rounding it again as u mentioned. I cannot round first as the values will be different. Its a general implementation which works for all other values except this one. – Shirish11 Jul 17 '18 at 12:06
0

Have you tried using the round function without any other arguments?

double h = 128.015999031067; double d = Math.Round(h*1000);

Ralph King
  • 994
  • 1
  • 9
  • 19