Search code examples
c#mathtypesdoubledecimal

Performing Math operations on decimal datatype in C#?


I was wondering if the above was at all possible. For example:

Math.Sqrt(myVariableHere);

When looking at the overload, it requires a double parameter, so I'm not sure if there is another way to replicate this with decimal datatypes.


Solution

  • In most cases involving a decimal (currency etc), it isn't useful to take a root; and the root won't have anything like the expected precision that you might expect a decimal to have. You can of course force it by casting (assuming we aren't dealing with extreme ends of the decimal range):

    decimal root = (decimal)Math.Sqrt((double)myVariableHere);
    

    which forces you to at least acknowledge the inherent rounding issues.