1

I am using Math.Round(decimal d, int decimals) in C# to round decimals to a specified number of decimal places. I can round to 15 decimal places, but when I try and round to 16, for example, I get the following exception:

An unhandled exception of type 'System.ArgumentOutOfRangeException' occurred in mscorlib.dll Additional information: Rounding digits must be between 0 and 15, inclusive.

Is there any way of rounding to a higher number of decimal places, perhaps without the use of Math.Round?

To give slightly more background to the problem, I am calculating irrational mathematical constants such as 'pi' and 'e', and letting the user specify the number of decimal places to calculate to. The boolean to check whether or not the value and the previous value are identical to the given accuracy is as follows:

Math.Round(valuePrevious, decPlaces) == Math.Round(valueCurrent, decPlaces)
James Vickery
  • 732
  • 3
  • 10
  • 23

2 Answers2

8

You're not using Math.Round(decimal d, int decimals), you're using Math.Round(double d, int decimals). Make sure that valuePrevious is decimal, not double.

Doubles can be rounded to 15 digits max. Decimals to 28 digits. That's the maximum precision these types support.

Jakub Lortz
  • 14,616
  • 3
  • 25
  • 39
  • I'll change the values to decimal rather than double. Is there any way of also exceeding decimal's limit of 28 digits? Ideally there would be no limit. – James Vickery Nov 14 '15 at 23:58
0

You may want to use Decimal.Round() instead of Math.Round()

Decimal.Round supports up to 28 decimal places

https://msdn.microsoft.com/en-us/library/6be1edhb(v=vs.110).aspx

Juan
  • 3,675
  • 20
  • 34