0

I have a double value: 0.314285 which I want to Round off to 5 decimal places. From a mathematical point of view my expectant result is: 0.31429. In my code I use the Math.Round with MidPointRounding.AwayFromZero parameter overload, the resultant output being: 0.31428.

Is there another way to implement to have the output result as: 0.31429??

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
jdennoh
  • 43
  • 9
  • How did you declare the `0.314285` value? Basically, you should read this [article](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.8#rounding-and-precision) Using a decimal will solve your problem – Pavel Anikhouski Jan 19 '20 at 16:25
  • [Related](https://stackoverflow.com/questions/977796/why-does-math-round2-5-return-2-instead-of-3) – Sнаđошƒаӽ Jan 19 '20 at 16:32
  • @Sнаđошƒаӽ This is related to `MidpointRounding`, `Round` uses `MidpointRounding.IsEven` by default, but OP explicitly sets it to `AwayFromZero` – Pavel Anikhouski Jan 19 '20 at 16:43

3 Answers3

5

You should read the rounding and precision article. The real representation of your number in memory can be something like 0.3142849999999999, and therefore you are getting 0.31428 result. Using a decimal type can help to solve this issue

var value = 0.314285m;
var result = Math.Round(value, 5, MidpointRounding.AwayFromZero); //0.31429
Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
0
public static double RoundUp(double i, int decimalPlaces)
{
    var power = Math.Pow(10, decimalPlaces);
    return Math.Ceiling(i * power) / power;
}


RoundDown(0.314285, 5); //0.31429
Kevin
  • 16,549
  • 8
  • 60
  • 74
Eugene Ogongo
  • 335
  • 3
  • 12
-1
Math.Round(decimal number to round, int number of decimal places)

I think this should work for what you are trying to do.