Error when calculating decimal value

Asked

Viewed 108 times

3

I need to calculate the interest value, this is the code:

public async Task<decimal> CalculatesInterestAsync(decimal valorInicial, int meses, decimal juros)
{
    var valorFinal = (decimal)Math.Pow((double)Decimal.Multiply(valorInicial, 1 + juros), meses);

    return await Task.FromResult(valorFinal);
}

The value I’m passing on is:

valorInicial = 100
meses = 5
juros = 0.01M

I need the ultimate value to be 105.10, but it is always returned 10510100501M.

What could I be doing wrong? Since the top 5 houses are the ones I need.

1 answer

7


Your formula is wrong, the correct one:

using static System.Console;
using static System.Math;

public class Program {
    public static void Main() => WriteLine(CalculatesInterest(100M, 5, 0.01M));
    public static decimal CalculatesInterest(decimal valorInicial, int meses, decimal juros) => decimal.Round(valorInicial * (decimal)Pow(1.0 + (double)juros, meses), 2);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference.

I find it unfortunate that it does not have the power to decimal, although it does not cause major problems in most situations. Understand that the value obtained is not accurate, if you need it you need to take other steps and depending on where you use it you need to observe the legislation to use correctly, I used the amount of decimals that asks the question, but it is not always correct according to the legislation.

Note that I took out the asymchronism because it is greatly worsening the performance (this is an expensive mechanism), it does not make the slightest sense to make such a simple calculation asynchronously. In fact this mechanism should only be used for IO, not for processing. Do not use things, even more complex, without deeply understanding why this exists and knowing all the consequences of use.

  • Perfect answer, thank you for the great help Maniero

Browser other questions tagged

You are not signed in. Login or sign up in order to post.