I am relatively new to programming (3-5 months) and have to write a program that prompts users for input (number of items ordered at a restaurant), performs some monetary calculations, and then requests monetary input/payment. I am using Dev-C++ by Bloodshed on Windows XP.
I am running into a problem with rounding the total expense to two decimal places.
EX: If you input 5 for numOfBurgers, numOfFries, and numOfSodas, the total to be paid comes to $17.861 and I need it to round down (not necessarily truncate) to 17.86 so that the payment portion always works properly.
I have read online to add 0.005 to my double, multiply it by 100, cast it to an int, cast it back to a double, and then divide by 100. I begin this process on line 47, and the payment portion of the program begins on line 55.
This methodology works, and the program runs properly every time, but I am not convinced that this is good practice, and can find no reference to situations like this in any of my textbooks or on the web. I would like to know what the best practice would be for tackling problems like this (rounding and truncating values stored in memory).
I have supplied my code below (using Dev-C++ by Bloodshed, Windows XP), thanks in advance for any help! - /*
-
Name: FastFood.cpp
-
Written by Calvin Kosterman
-
Last modified on December 14th at 11:48pm
-
Description: Program that receives a fast food order from a customer,
-
calculate the total expenses including GST, prompts the user for
-
their payment, and calculates the customer's change accordingly.
-
*/
-
-
#include <iostream>
-
-
using namespace std;
-
-
int main()
-
-
{ // Begin int main()
-
-
int
-
numOfBurgers, // Number of burgers ordered
-
numOfFries, // Number of fries ordered
-
numOfSodas, // Number of sodas ordered
-
totalBillToInt; // Truncates totalBill
-
-
const double
-
burgerPrice = 1.49, // Price for one burger
-
friesPrice = 0.89, // Price for one order of fries
-
sodaPrice = 0.99, // Price for one soda
-
salesTax = 1.06; // Sales tax charged on order
-
-
double
-
totalBill, // Total amount charged for order
-
totalBillToDouble, // Truncated value of totalBill
-
amountTendered, // Amount of money paid towards totalBill
-
amountRemaining, // Amount of money unpaid towards totalBill
-
change; // Amount of money overpaid towards totalBill
-
-
-
cout << "Enter number of burgers ordered\n";
-
cin >> numOfBurgers;
-
cout << "\n\nEnter number of fries ordered\n";
-
cin >> numOfFries;
-
cout << "\n\nEnter number of sodas ordered\n";
-
cin >> numOfSodas;
-
totalBill = (((numOfBurgers * burgerPrice) + (numOfFries * friesPrice) + (numOfSodas * sodaPrice)) * salesTax);
-
-
-
totalBillToInt = ((totalBill + 0.005) * 100); // Rounds totalBill
-
totalBillToDouble = totalBillToInt; // to nearest penny
-
-
totalBillToDouble = (totalBillToDouble / 100); // Rounded value of
-
// totalBill
-
-
cout << "\n\nYour total comes to: $" << totalBillToDouble << endl << endl;
-
-
cout << "\n\nEnter amount tendered:\n";
-
cin >> amountTendered;
-
-
amountRemaining = (totalBillToDouble - amountTendered);
-
-
while (amountRemaining > 0.00)
-
-
{ // Begin while (amountRemaining > 0.00)
-
-
cout << "You still owe: $" << amountRemaining << endl;
-
cout << "\n\nEnter amount tendered:\n";
-
cin >> amountTendered;
-
amountRemaining = (amountRemaining - amountTendered);
-
-
if (amountRemaining < 0.00)
-
-
{ // Begin if (amountRemaining < 0.00)
-
-
change = (amountRemaining * -1.00);
-
cout << "\n\nYour change is $" << change << "\n\n\n***Please come again!***\n\n\n";
-
system("PAUSE");
-
return 0;
-
-
} // End if (amountRemaining < 0.00)
-
-
} // End while (amountRemaining > 0.00)
-
-
-
if (amountRemaining == 0.00)
-
-
{ // Begin if (amountRemaining == 0.00)
-
-
cout << "\n\n\n***Please come again!***\n\n\n" ;
-
system("PAUSE");
-
return 0;
-
-
} // End if (amountRemaining == 0.00)
-
-
-
if (amountRemaining < 0.00)
-
-
{ //Begin if (amountRemaining < 0.00)
-
-
change = (amountRemaining * -1.00);
-
cout << "\n\nYour change is $" << change << "\n\n\n***Please come again!***\n\n\n";
-
system("PAUSE");
-
return 0;
-
-
} // End if (amountRemaining < 0.00)
-
-
} // End int main()
2 2800
First, you are using C++, so please stop casting. A C++ cast usually means a) you are calling relic C function that has a void* argiment or some such, or b) your design is screwed up. A cast always tells the compiler: Shut up and just do what I tell ya!!
Second, floating point cannot be used for money applications dues to the automatic rounding. In fact, in the EU there are laws prohibiting this practice. Floating point is intended for scientific work where extreme precision is not required. Beginners fall into this trap because of the handy decimal point.
Third, you are using integer operators on floating point. Read this:
Generally, you cannot use operators like ==, !=, >, <, <=, >=, etc wth floating point numbers.
Due to the automatic rounding, these operators may report a condition as true when the numbers
are only close in value.
Google for Floating Point Arithmetic or read IEEE 754 standard specification for details.
To compare two floating point numbers, you have to establish a sigma error tolerance. -
if (fabs(i - j) < 0.000001) { ... // almost equal }
-
----------------------------------------------------------------------
Also, be aware of this:
Symbolic constants like 1.1 are double. A double is larger than a float so your compiler is giving
you a warning about truncation and possible loss of data as the double is converted to a float.
You should create the constant as a float by coding: -
float j = 1.1f; /* or 1.1F */
-
Further, float is a type developed in the years of computers with small memories.
Unless you can write a specific reason on paper as to why you need a float,
I recommend you use double throughout.
Fourth, use integers in your program and keep the money in pennies. An int with a value of 1761 can be displayed as $17.61 or $1761, etc as determined by the display function.
Thank you weaknessforcats, that makes perfect sense now.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: Ron Adam |
last post by:
With all the discussion about numbers here and particularly in regards
to prePEP concerning decimal data types got me wondering about how
numbers are handled when it comes to rounding. And if that...
|
by: spebola |
last post by:
I am using vb.net 2003 professional and I get the following results
when using the round method:
dim Amount as decimal = 180.255
Amount = Amount.Round(Amount, 2)
Amount now contains 180.25. ...
|
by: Zorpiedoman |
last post by:
Howcome:
Dim D as decimal = .5D
msgbox d.Round(D, 0)
this returns "0"
Now when I went to school .5 rounds UP to 1 not DOWN to zero?????!!!
Documentation says this, but what the heck are...
|
by: Jiri Nemec |
last post by:
Hello all,
I have got one table with rounding values, table contains
prices and round types.
id price_from price_to rounding
1 0 1500 0.1
2 1500 ...
|
by: Jason |
last post by:
I am having a rounding problem in a value i am trying to display in VB.NET.
If I have the following code:
Dim x As Single = 2726.795
Dim y As Single = Math.Round(2726.795, 2)
Dim s as String =...
|
by: Marcus |
last post by:
Hi, was wondering if anyone knows a good algo for rounding time to a
desired interval.
For instance, I have data set that is timestamped in second resolution
and I need to modify that data to be...
|
by: jdrott1 |
last post by:
i'm trying to round my currency string to end in 9. it's for a
pricing application.
this is the function i'm using to get the item in currency:
FormatCurrency(BoxCost, , , , TriState.True)
if...
|
by: Spoon |
last post by:
Hello everyone,
I don't understand how the lrint() function works.
long lrint(double x);
The function returns the nearest long integer to x, consistent with the
current rounding mode. It...
|
by: bdsatish |
last post by:
The built-in function round( ) will always "round up", that is 1.5 is
rounded to 2.0 and 2.5 is rounded to 3.0.
If I want to round to the nearest even, that is
my_round(1.5) = 2 # As...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Sonnysonu |
last post by:
This is the data of csv file
1 2 3
1 2 3
1 2 3
1 2 3
2 3
2 3
3
the lengths should be different i have to store the data by column-wise with in the specific length.
suppose the i have to...
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |