+ 2

Why is 5 - 4.99 = 0.0100002289? [SOLVED]

When subtracting two float numbers (cost and moneyPaid) the result is (according to the program) 0.0100002289 (also stored in a float). Why does this happen? You don't need a mathematician to figure out that it's wrong. Using other other values still led to similar results. Relevant Code (very shortened, no user interaction): using System; namespace ChangeCalculator { class Program { static float cost = 4.99F; static Coins input; static float moneyPaid; static float changeAmount; static Coins changeCoins; static void Main() { moneyPaid = 5.00F changeAmount = moneyPaid - cost; //changeAmount = 0.0100002289 changeCoins = calculateChange(changeAmount); displayReturn(changeCoins); } } }

15th Jan 2017, 5:14 PM
Maike
4 Answers
+ 8
float are only accurate to 6 digits so 4.99 is actually something b/w 4.990001 to 4.989999
13th Jan 2017, 7:04 PM
Caffeinated Gamer YT
Caffeinated Gamer YT - avatar
+ 1
I got 0.0100002 for c++ language which is right. Yours is a little different because of those static variables and methods.
13th Jan 2017, 6:46 PM
David Oats
David Oats - avatar
+ 1
Sorry, my fault. It's 5 - 4.99. However it's not 5.0000002289 - 4.9900000000.
13th Jan 2017, 6:53 PM
Maike