I'm just getting into Unity and C#, trying to code a script for calculator with 2 input fields, buttons for necessary arithmetic operations and a "Result" text field. All basic functions are working fine, but while messing with the input values for Power I encountered this issue of overflowing value in resulting variable. Googling various solutions I settled with this one shown in the code below. Problem is, mentioned issue still persists, and when testing the app I am still getting this error in the console:
OverflowException: Arithmetic operation resulted in an overflow. System.Decimal.op_Explicit (System.Single value) (at <695d1cc93cca45069c528c15c9fdd749>:0)
I assume that the way checked-keyword is implemented in my code might be incorrect, but I can't figure out in what way.
My initial idea was to convert resulting value to double and set a ceiling for it, but as I understand the calculation still being done and overflow happens before I even compare value to the threshold, so it was decided to try other tools. If any other ways to avoid this error exist - it would be awesome.
public class Calculator : MonoBehaviour
{
public Text Result;
public InputField FirstNumber;
public InputField SecondNumber;
public void OnClickPower()
{
if (FirstNumber.text.ToString() != "" & SecondNumber.text.ToString() != "")
{
Debug.Log("Numbers Unequal > success");
decimal i = decimal.MaxValue;
int j;
float k;
j = int.Parse(FirstNumber.text);
Debug.Log("First number > " + j);
j = int.Parse(FirstNumber.text);
Debug.Log("Second number > " + j);
k = Mathf.Pow(float.Parse(FirstNumber.text), float.Parse(SecondNumber.text));
Debug.Log("Result in float > " + k);
decimal l = Convert.ToDecimal(k);
Debug.Log("Result in decimal > " + l);
try
{
l = checked(i + l);
Result.text = l.ToString();
}
catch (OverflowException ex)
{
Debug.Log(ex);
Result.text = l.ToString();
}
}
else
{
Result.text = "NO NUMBERS";
}
}
};