Rounding in C++

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Grandia2
    New Member
    • Sep 2008
    • 2

    Rounding in C++

    Hello all. I am trying to round a float number and then have that number added to a total of numbers. the number i am trying to round up is the one called tax. It will take the last digit and round up by one. I have provided the code for just this occasion. Remember, i am having trouble getting the variable tax to round up one decimal digit. And that value needs to go and then be added to the total cost variable. THANK YOU!

    #include <iostream>
    #include <string>
    #include <iomanip>

    using namespace std;

    int main (void)
    {

    //declarations
    int guests;

    float costPerPerson;
    float totalCost;
    float tax;
    float tip;
    float food;

    //string caterername;
    char caterername [256];

    const float SalesTax = .06;
    const float Gratuity = .15;


    //User will enter name of caterer, cost per person, and number of guests
    //values will be stored and retrieved later.

    cout << "Please enter a caterer name: ";
    //cin >> caterername;
    cin.getline (caterername,25 6); //code structure taken from cplusplus.com
    // >> endl;
    //cout << caterername;
    //>> endl;

    cout << "Please enter the cost per person: $";
    // << endl;
    cin >> costPerPerson;
    //<< endl;
    //cout << costPerPerson;

    cout << "Please enter the number of guests attending: ";
    //<< endl;
    cin >> guests;
    //>> endl;
    //cout << guests;

    //Values entered by the user will be retrieved and used to calculate
    //the meal information
    food = costPerPerson * float(guests); //calculates the cost of food only
    tax = food * SalesTax; //calculates the cost of the sales tax
    tip = food * Gratuity ; //calculates the cost of the tip
    totalCost = food + tax + tip; //calculates the total cost of the meal


    cout << endl;
    cout << endl;
    cout << endl;

    //Computer will print a reciept for the user containing
    //caterer name, cost of food, tax, tip, and total cost.
    cout <<" Here is the estimated cost reciept: "
    << setw (6)
    << setprecision (2)
    << showpoint
    << fixed
    << endl;

    cout << "Caterer Name: "
    << caterername
    << endl;

    cout << "Cost of food: $"
    << food
    << endl;

    cout << setw (6)
    << "Tax: $"
    << setprecision(2)
    << tax
    <<endl;

    cout << "Tip: $"
    << tip
    <<endl;

    cout << "Total Cost: $"
    << totalCost
    << endl;

    return 0;



    }

    I need them to be rounded up such as the way you would round money. $23.453 = $23.46. I need the last digit in that area to round up to the next highest digit! It is to calculate the tip. So any number greater than 0 will automatically round up.
  • scruggsy
    New Member
    • Mar 2007
    • 147

    #2
    One way to do it: add 0.005, multiply by 100, and cast to an integer, then divide by 100 and store the result in a float.

    Comment

    • Grandia2
      New Member
      • Sep 2008
      • 2

      #3
      Could i please see that in a formula. To me it looks kind of jumbled. I got tax+.005 * 100 (int tax)??? /100 = float tax?

      Im very sure that that is not right at all. How should it look?

      Comment

      • Airslash
        New Member
        • Nov 2007
        • 221

        #4
        can't you just use the ceil() method for it? Dunno if it exists in C++ but it should round up your number to the next highest int value. So if you multiply by 100 first for example to get rid of the unwanted decimals behind the , and then use ceil(), you'll get the next highest value normally

        Comment

        • donbock
          Recognized Expert Top Contributor
          • Mar 2008
          • 2427

          #5
          How vital is it to be absolutely confident that you end up with precisely the right answer? That is, is this a homework assignment or is it software for a payroll system that will actually write checks for real people?

          Rounding algorithms for a homework assignment can be ad hoc.

          Rounding algorithms for software that deals with real money should follow the accepted rules of accounting. I don't know what those are; but I know they're not ad hoc.

          Comment

          • donbock
            Recognized Expert Top Contributor
            • Mar 2008
            • 2427

            #6
            Let's specify the desired behavior for a function that rounds to the nearest integer. We'll call that function IntRound().
            IntRound(4.2) = 4
            IntRound(4.8) = 5
            IntRound(4.5) = 4 or 5 (we don't really care which)
            IntRound(-4.2) = -4
            IntRound(-4.8) = -5
            IntRound(-4.5) = -4 or -5 (we don't really care which)
            The <math.h> library in C (and the <cmath> library in C++) provide two functions that might be useful:
            double ceil(double x) = smallest integer no less than x
            double floor(double x) = largest integer no greater than x
            ceil(4.2) = 5 ....... floor(4.2) = 4
            ceil(4.8) = 5 ....... floor(4.8) = 4
            ceil(4.5) = 5 ....... floor(4.5) = 4
            ceil(-4.2) = -4 ..... floor(-4.2) = -5
            ceil(-4.8) = -4 ..... floor(-4.8) = -5
            ceil(-4.5) = -4 ..... floor(-4.5) = -5

            For non-negative x, floor(x) works like a truncation function -- it discards the fractional part and returns only the integer part. For the rounding function you want to truncate [round down] if the fractional part is less than 0.5 and round up if it is more than 0.5. Consider this first draft of IntRound for non-negative input:
            Code:
            int IntRound(double x) {
               return (int) floor(x + 0.5);
               }
            [I]... or ...[/I]
            int IntRound(double x) {
                return (int) ceil(x - 0.5);
                }
            What about when the input is negative? It still works!
            IntRound(4.2) = floor(4.7) = 4
            IntRound(4.8) = floor(5.3) = 5
            IntRound(4.5) = floor(5.0 +/- epsilon) = 4 or 5
            IntRound(-4.2) = floor(-3.8) = -4
            IntRound(-4.8) = floor(-4.3) = -5
            IntRound(-4.5) = floor(-4.0 +/- epsilon) = -4 or -5
            (The "+/- epsilon" is due to the fact that floating point arithmetic can introduce a very small error, here called epsilon. This inaccuracy is present in all the cases, but it is only relevant to the outcome of floor in two of them.)

            Scruggsy suggested casting a double into an int because doing so commonly has the result as the floor() function (at least for positive inputs). For instance:
            Code:
            int IntRound(double x) {
               return (int) (x + 0.5);
               }
            However, the C Standard makes no such guarantee. Depending on your compiler, casting a double to an int might ...
            > be the same as the floor function
            > be the same as the ceil function
            > be the same as the IntRound function
            > always round towards zero
            > or do something else
            Relying on implementation-dependent behavior will get you in trouble sooner or later.

            Suppose you have a double whose value is a price in dollars and you want to round to the nearest penny. You can accomplish this with IntRound too:
            Code:
            double roundedPrice = (double) IntRound(price * 100.0) / 100.0;

            Comment

            • whodgson
              Contributor
              • Jan 2007
              • 542

              #7
              I think the setprecision() function rounds up but not unless the less significant digit to be dropped is >=5 .The <iomanip> header file defines the setprecision()
              function.
              for example
              Code:
              const double PI=3.1415926535897323846;
              cout<<PI<<endl;//prints3.14159 on this machine
              cout<<setprecision(10)<<PI<<endl;//prints 3.141592654.

              Comment

              Working...