I need to be able to use the standard math functions on decimal numbers. Accuracy is very important. double
is not an acceptable substitution. How can math operations be implemented with decimal numbers in C#?
edit I am using the System.Decimal
. My issue is that System.Math
does not work with System.Decimal
. For example, the following functions do not work with System.Decimal
:
You should become efficient in using the four basic operations involving decimals—addition, subtraction, multiplication, and division. To add or subtract decimals, just line up the decimal points and then add or subtract in the same manner you would add or subtract whole numbers.
In C#, Decimal Struct class is used to represent a decimal floating-point number. The range of decimal numbers is +79,228,162,514,264,337,593,543,950,335 to -79,228,162,514,264,337,593,543,950,335.
C# decimal precision The decimal type is a 128-bit floating point data type; it can have up to 28-29 significant digits. The following example compares the precision of the float , double , and the decimal types. Program.cs. float x = 1f / 3f; double y = 1d / 3d; decimal z = 1m / 3m; Console. WriteLine(x); Console.
Well, Double uses floating point math which isn't what you're after unless you're doing trigonometry for 3D graphics or something.
If you need to do simple math operations like division, you should use System.Decimal.
From MSDN: The decimal keyword denotes a 128-bit data type. Compared to floating-point types, the decimal type has a greater precision and a smaller range, which makes it suitable for financial and monetary calculations.
Update: After some discussion, the problem is that you want to work with Decimals, but System.Math only takes Doubles for several key pieces of functionality. Sadly, you are working with high precision numbers, and since Decimal is 128 bit and Double is only 64, the conversion results in a loss of precision.
Apparently there are some possible plans to make most of System.Math handle Decimal, but we aren't there yet.
I googled around a bit for math libraries and compiled this list:
Mathdotnet, A mathematical open source (MIT/X11, LGPL & GPL) library written in C#/.Net, aiming to provide a self contained clean framework for symbolic algebraic and numerical / scientific computations.
Extreme Optimization Mathematics Library for .NET (paid)
DecimalMath A relative newcomer, this one advertises itself as: Portable math support for Decimal that Microsoft forgot and more. Sounds promising.
DecimalMath contains all functions in System.Math
class with decimal
argument analogy
Note : it is my library and also contains some examples in it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With