I have a library that modifies an input (adding or multiplying the input with one or more stored variables). These variables are stored as floats. Usually, the input is also a float, but in some cases it's an int. I'm concerned about the accuracy of this.
float GetValue(float input)
{
foreach (float modifier in various_data_sources)
{
if (isFactor)
input = input * modifier;
else
input = input + modifier;
}
return input;
}
void MainLogic()
{
int defaultValue = 3;
// If the modifier is 2 (add), I expect the final modified int to be 5:
DoSomeIntThing((int) GetValue(defaultValue));
}
Is there anything I can do to make this safer? The value modifications need to be dynamic, and separating the modifications to integer operations and floating point operations will be a mess. Is this as unsafe as I think it is, or will an operation like (int)(2.0f+(float)3)
always yield the hoped-for result?