How to fix this calculation error?

Why is my taxTotal rounding up like it should but why does finalTotal not round up? An example of this is purchasing the item that costs $21.00. With my subtotal at $21.00 and the calculated taxTotal equaling $1.58, then why does my finalTotal come out to $22.57?

Here is the function from my source code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
double checkout(double PurchaseSubTotal, double inBankBalance)
{
	srand(time(NULL)); //NULL is defined as 0 (zero)
	ofstream outFile; 
	
	int min = 1000;
	int max = 9999;
	int ReceiptID = rand()%1000 +1;
	int BankDebitID = (rand()%(max-min)+min);
	double taxTotal = 0.0750 * PurchaseSubTotal;
	double finalTotal = PurchaseSubTotal + taxTotal;
	double MoneyLeft = inBankBalance - finalTotal;
	double MoneyRemaining = (MoneyLeft * -1);

	cout << "\nWelcome to checkout!" << endl;
	
	if (inBankBalance < finalTotal)
	{
		cout << "US Debit: Declined" << endl;
		cout << "Unfortunately, you do not have enough funding in your piggy bank to complete this purchase!" << endl;
		cout << "You are short by exactly: $" << MoneyLeft << endl;
		cout << "Thank you! Please visit the Toy Store another time!" << endl;
	}

	else
	{
		outFile.open("ToyStoreReceipt.txt");   // Saving receipt from purchase to a text file on computer
		outFile << fixed << setprecision(2);
		outFile << "Subtotal: $" << PurchaseSubTotal<< endl; 
		outFile << "Sales tax: 7.5%" << endl;
		outFile << "Sales tax applied: $" << taxTotal << endl;
		outFile << "Total price: $" << finalTotal << endl;
		outFile << "EFT Debit: **** **** **** " << BankDebitID << endl;
		outFile << "US Debit: Approved" << endl;
		outFile << "Receipt ID: " << ReceiptID << endl;
		outFile << "\nThank you for your purchase! Please give our store a visit another time!" << endl;
		outFile.close();
		return MoneyLeft;
	}
}
closed account (48T7M4Gy)
Sounds like rounding errors creeping in due to the limitations of double.

There are a couple of ways of eliminating this and one way is to perform all the calculations on cents as integers and convert to dollars as required.
kemort,

Could you show me a basic example of how to do this?
I would greatly appreciate it!

-MisterTams
closed account (48T7M4Gy)
Better still read this for a more comprehensive understanding. It's just simple arithmetic so don't make it complicated for yourself - try it with pencil and paper :)

http://stackoverflow.com/questions/4008395/rounding-problem-with-double-type
Topic archived. No new replies allowed.