I have this switch statement that decreases the double itemCost (originally 0.80) by 0.20 each time. When it reaches 0.00 i want to execute some code. It works fine until it gets to 0.00 but instead of being 0.00 itemCost becomes 5.55111512312578E-17.
Output values for itemCost as I press the button which executes switch statement are:
0.60, 0.40, 0.20, 5.55111512312578E-17, -0.20, -0.40 etc
Code:
switch (codeString)
{
case "20":
{
userAmount = userAmount + 0.20;
itemCost = itemCost - 0.20;
Console.WriteLine("" + itemCost);
if (itemCost == 0.00)
{
giveChange();
labelInstructions.Text = "giveChange";
}
else
{
string tempString = string.Format("{0:N2}", itemCost);
labelInstructions.Text = "Please insert £" + tempString;
}
break;
}
}
Anyone know why this weird behavior occurs and how to fix it?
Since you are dealing with currency, you should switch over and use the Decimal datatype.
Floats and Doubles encounter very, very strange behavior when dealing with addition and subtraction as you get closer to 0.0.
It is critical when programming on all platforms to be very wary of floating point math when you need absolute precision. For example, game developers are
forced to use floating-points, due to graphics-card, graphics-library, and performance restrictions. Typically, when they want to see if a value is zero, instead of comparing against zero, they do the following (pseudo code)
If you absolutely cannot switch to decimal, you can do something similar. If MyDouble is within Epsilon of Zero, where Epsilon is a const in the neighborhood of 0.00001, then force your value to zero. This is not recommended is 99% of scenarios. You really MUST use Decimal for currency, otherwise you will end up charging customers the wrong amount or suffering seemingly-random bugs.