'What does this error mean, and how do I rectify it?
system.overflow exception: value too small or too large
I'm busy with a loan calculator app. In the code below, I'm trying to calculate the loan payment (paymentD; payment) to push into a loan object. The user values which are used to calculate the loan are: Loan Amount (amountD), Loan Rate (monthlyRate;rateD), and Loan Term (term).
In the values mentioned above, the Loan Amount and Loan Rate are decimals, and the term is of type int. As such, I had to convert the decimal type to the double type in order to calculate paymentD, before reconverting the answer back to a decimal (payment).
However when I run the code, it only works when I enter a whole number into the rate value. When I try to use a fraction value (say 3.5), it throws this error. When debugging for the 3.5, payment returns NaN
.
How do I fix this? integer value added to the rate
Code:
private decimal CalcMonthlyPayments(decimal amount, int term, decimal rate)
{
var monthlyRate = CalcMonthlyRate(rate);
var rateD = Convert.ToDouble(monthlyRate);
var amountD = Convert.ToDouble(amount);
var paymentD = (amountD * rateD) / (1 - Math.Pow(1 + rateD, -term));
var payment = Convert.ToDecimal(paymentD);
return payment;
}
private decimal CalcMonthlyRate(decimal rate)
{
return rate / 1200;
}
private decimal CalcMonthlyInterest(decimal balance, decimal monthlyRate)
{
return balance * monthlyRate;
}
Solution 1:[1]
You have a value that is too big or too small for the data-type being used.
Here is an example (of a different data type) that shows how you can "pre check" on ~some values.
https://docs.microsoft.com/en-us/dotnet/api/system.int16.maxvalue?view=net-6.0#examples
But if you have something like this:
Int16 result = Int16.MaxValue + 100;
you can see the issue. The code is trying to go 100 "beyond" the supported max.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |