-1

I'm in .NET (C#), and I have a piece of code that basically does the following:

decimal value = decimal.Parse(s);
long result = (long)(value * 10000M);

However, I can't use 10000 directly since the number of decimal places is variable (in this case, it's stored as 4). Is there a way I can use this 4 to get to 10000M?

I was thinking on something like Math.Pow, but it doesn't seem to be available for decimal types. I was also thinking on a simple function that does multiplication in a loop, but if something already exists in the .NET framework, then I'd rather use that.

Arturo Torres Sánchez
  • 2,751
  • 4
  • 20
  • 33

3 Answers3

2

Here's a simple method to raise a decimal to a non-negative integer power.

public static decimal Pow( decimal x, int n )
{
    if( n < 0 )
    {
        throw new ArgumentOutOfRangeException( "n" );
    }

    decimal result = 1;
    decimal multiplier = x;

    while( n > 0 )
    {
        if( ( n & 1 ) > 0 ) result *= multiplier;
        multiplier *= multiplier;
        n >>= 1;
    }

    return result;
}
Kyle
  • 6,500
  • 2
  • 31
  • 41
1

I don't like to use Math.Pow because it uses a generic math equation, and so is often slower (unless you are using fractional exponents which it looks like you are not). Instead I would write an extension method like this:

public static long ToPower(this decimal val, int pow)
{
    decimal ret = 1;
    for(int i = 0; i < pow; i++)
        ret *= val;
    return (long)ret;
}

Which can be called like:

myDecimal.ToPower(4);

EDIT: I just ran a test to validate times. It seems that Math.Pow is now faster than a basic loop for any integer power above 50. The times are minimal, but often times when I am doing power math, I am doing a lot of calculations.

If you are doing this calculation a few times, then there is no need to use anything but Math.Pow as the performance changes are minimal.

druidicwyrm
  • 480
  • 2
  • 11
1

Just cast it to a decimal after raising it to the power.

decimal value = decimal.Parse(s);
int power = 4;
long result = (long)(value * (decimal)Math.Pow(10, power));
Alex Wiese
  • 8,142
  • 6
  • 42
  • 71