float calculation issue
Here is my simple bonus assignment program. The issue I met with is, the ResultTotalReceived is larger then ResultTotalSent, which violates corporation policy and exception is thrown.
The program works in this way,
1. At source side, calculate and assign the bonus according to each worker's factor (100F for worker1 and 300F for worker2 in my sample). All figures are float type.
2. Convert the float type to string and sent to another destination to store the bonus into storage;
3. The detination side will perform basic checking rules before storing the data, e.g. the total bonus assigned should not exceed the total bonus available at source side.
In my code below,
The value of ResultTotalSent is 199.321, and the value of ResultTotalReceived is 199.321045, which is larger than ResultTotalSent.
My questions is,
1. If I want to solve this issue at source side, what is the elegant way to solve this issue? Currently, my temp solution is using ToString("F2"). Any issues with this solution?
2. Why there is such issue? It is the issue of ToString of Float class -- I have this suspecision is because ResultTotalSent is precise but after ToString conversion the result and conversion back at detination side, it is not precise?
static void Main(string args)
float TotalBonus = 199.321F;
float Worker1 = 100F;
float Worker2 = 300F;
float Result1 = TotalBonus * Worker1 / (Worker1 + Worker2);
float Result2 = TotalBonus * Worker2 / (Worker1 + Worker2);
float ResultTotalSent = Result1 + Result2;
string Result1String = Result1.ToString();
string Result2String = Result2.ToString();
// sending to another computer using string
// received from another computer using string
string ReceivedString1 = Result1String;
string ReceivedString2 = Result2String;
float Received1 = float.Parse(ReceivedString1);
float Received2 = float.Parse(ReceivedString2);
float ResultTotalReceived = Received1 + Received2;
// sanity checking failed, since ResultTotalReceived > TotalBonus
thanks in advance,
You can rarely depend on floating point operations to be precise. Never compare two floating point values with ==. Instead check if the difference is small enough. Since you use 3 decimals, you could check if the difference is less than 1/1000 (1/(10^3)).
if(System.Math.Abs(Value1 - Value2) < 0.001f)
//They're pretty much equal