-3

I have the following problem. When I try to round a number from a "double" type, it doesn't work as I expect it.

Consider the following code:

double d = 0.00498;
Console.WriteLine(Math.Round(d, 2)); // prints 0

The result that i am getting is wrong.

The program must print 0.01, and I have tried everything and nothing worked properly.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
K.Krunk
  • 85
  • 1
  • 9

3 Answers3

3

I think you need a second iteration for your desired result

double d = 0.00498;
double result1 = Math.Round(d, 3, MidpointRounding.AwayFromZero);
double result2 = Math.Round(result1 , 2, MidpointRounding.AwayFromZero);
Console.WriteLine(result2);

because 0.00498 results into 0.005 instead of 0.01

fubo
  • 44,811
  • 17
  • 103
  • 137
0

You expect to it rounds the number up with 2 decimal points.

Math.Ceiling(d * 100) / 100
0

The result is coming correct. You can try in excel application.

enter image description here

Regards, Nandkumar S.

Nandu
  • 103
  • 9