473,395 Members | 1,941 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Rounding values and storing the rounded value in a variable

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!


Expand|Select|Wrap|Line Numbers
  1. /*
  2.   Name: FastFood.cpp
  3.   Written by Calvin Kosterman
  4.   Last modified on December 14th at 11:48pm
  5.   Description: Program that receives a fast food order from a customer, 
  6.                calculate the total expenses including GST, prompts the user for
  7.                their payment, and calculates the customer's change accordingly.
  8. */
  9.  
  10. #include <iostream>
  11.  
  12. using namespace std;
  13.  
  14. int main()
  15.  
  16. { // Begin int main()
  17.  
  18.    int        
  19.       numOfBurgers,     // Number of burgers ordered
  20.       numOfFries,       // Number of fries ordered
  21.       numOfSodas,       // Number of sodas ordered
  22.       totalBillToInt;   // Truncates totalBill
  23.  
  24.    const double
  25.       burgerPrice = 1.49,      // Price for one burger
  26.       friesPrice = 0.89,       // Price for one order of fries
  27.       sodaPrice = 0.99,        // Price for one soda
  28.       salesTax = 1.06;         // Sales tax charged on order 
  29.  
  30.    double
  31.       totalBill,               // Total amount charged for order
  32.       totalBillToDouble,       // Truncated value of totalBill
  33.       amountTendered,          // Amount of money paid towards totalBill
  34.       amountRemaining,         // Amount of money unpaid towards totalBill
  35.       change;                  // Amount of money overpaid towards totalBill
  36.  
  37.  
  38.          cout << "Enter number of burgers ordered\n";
  39.          cin >> numOfBurgers;
  40.          cout << "\n\nEnter number of fries ordered\n";
  41.          cin >> numOfFries;
  42.          cout << "\n\nEnter number of sodas ordered\n";
  43.          cin >> numOfSodas;
  44.          totalBill = (((numOfBurgers * burgerPrice) + (numOfFries * friesPrice) + (numOfSodas * sodaPrice)) * salesTax);
  45.  
  46.  
  47.    totalBillToInt = ((totalBill + 0.005) * 100);       // Rounds totalBill
  48.    totalBillToDouble = totalBillToInt;                 // to nearest penny
  49.  
  50.    totalBillToDouble = (totalBillToDouble / 100);      // Rounded value of 
  51.                                                        // totalBill
  52.  
  53.    cout << "\n\nYour total comes to: $" << totalBillToDouble << endl << endl;
  54.  
  55.    cout << "\n\nEnter amount tendered:\n";
  56.    cin >> amountTendered;
  57.  
  58.    amountRemaining = (totalBillToDouble - amountTendered);
  59.  
  60.    while (amountRemaining > 0.00)
  61.  
  62.    {   // Begin while (amountRemaining > 0.00) 
  63.  
  64.       cout << "You still owe: $" << amountRemaining << endl;
  65.       cout << "\n\nEnter amount tendered:\n";
  66.       cin >> amountTendered;
  67.       amountRemaining = (amountRemaining - amountTendered);   
  68.  
  69.       if (amountRemaining < 0.00)
  70.  
  71.          {   // Begin if (amountRemaining < 0.00)
  72.  
  73.             change = (amountRemaining * -1.00);    
  74.             cout << "\n\nYour change is $" << change << "\n\n\n***Please come again!***\n\n\n";
  75.             system("PAUSE");
  76.             return 0;
  77.  
  78.          }   // End if (amountRemaining < 0.00)
  79.  
  80.    }   // End while (amountRemaining > 0.00)
  81.  
  82.  
  83.       if (amountRemaining == 0.00)
  84.  
  85.          {   // Begin if (amountRemaining == 0.00)
  86.  
  87.             cout << "\n\n\n***Please come again!***\n\n\n" ;
  88.             system("PAUSE");
  89.             return 0;
  90.  
  91.          }   // End if (amountRemaining == 0.00)
  92.  
  93.  
  94.       if (amountRemaining < 0.00)
  95.  
  96.          {   //Begin if (amountRemaining < 0.00)
  97.  
  98.             change = (amountRemaining * -1.00);    
  99.             cout << "\n\nYour change is $" << change << "\n\n\n***Please come again!***\n\n\n";
  100.             system("PAUSE");
  101.             return 0;
  102.  
  103.          }   // End if (amountRemaining < 0.00)
  104.  
  105. } // End int main()
Dec 19 '07 #1
2 2800
weaknessforcats
9,208 Expert Mod 8TB
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.

Expand|Select|Wrap|Line Numbers
  1. if (fabs(i - j) < 0.000001) { ... // almost equal }
  2.  
----------------------------------------------------------------------

Also, be aware of this:
Expand|Select|Wrap|Line Numbers
  1. float var = 1.1;
  2.  
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:
Expand|Select|Wrap|Line Numbers
  1. float j = 1.1f;    /* or 1.1F */
  2.  
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.
Dec 19 '07 #2
Thank you weaknessforcats, that makes perfect sense now.
Dec 20 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

0
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...
4
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. ...
8
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...
2
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 ...
5
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 =...
5
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...
18
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...
5
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...
30
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
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...
0
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...
0
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...
0
Oralloy
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,...
0
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...
0
tracyyun
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...
0
agi2029
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,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.