简体   繁体   中英

Rounding to more than 15 decimal places in C#

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)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM