473,569 Members | 2,705 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Rounding in C++

2 New Member
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.
Sep 28 '08 #1
6 2933
scruggsy
147 New Member
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.
Sep 28 '08 #2
Grandia2
2 New Member
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?
Sep 28 '08 #3
Airslash
221 New Member
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
Sep 28 '08 #4
donbock
2,426 Recognized Expert Top Contributor
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.
Sep 29 '08 #5
donbock
2,426 Recognized Expert Top Contributor
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:
Expand|Select|Wrap|Line Numbers
  1. int IntRound(double x) {
  2.    return (int) floor(x + 0.5);
  3.    }
  4. ... or ...
  5. int IntRound(double x) {
  6.     return (int) ceil(x - 0.5);
  7.     }
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:
Expand|Select|Wrap|Line Numbers
  1. int IntRound(double x) {
  2.    return (int) (x + 0.5);
  3.    }
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:
Expand|Select|Wrap|Line Numbers
  1. double roundedPrice = (double) IntRound(price * 100.0) / 100.0;
Sep 30 '08 #6
whodgson
542 Contributor
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
Expand|Select|Wrap|Line Numbers
  1. const double PI=3.1415926535897323846;
  2. cout<<PI<<endl;//prints3.14159 on this machine
  3. cout<<setprecision(10)<<PI<<endl;//prints 3.141592654.
Sep 30 '08 #7

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

Similar topics

11
6632
by: cj | last post by:
Lets assume all calculations are done with decimal data types so things are as precise as possible. When it comes to the final rounding to cut a check to pay dividends for example in VB rounding seems to be done like this 3.435 = 3.44 3.445 = 3.44 Dim decNbr1 As Decimal
18
2203
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 an item is 41.87 i want the application to bring it up to 41.89 if an item is 41.84 i want the application to round down to 41.79 does anyone...
206
13169
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
248
1510
by: md | last post by:
Hi Does any body know, how to round a double value with a specific number of digits after the decimal points? A function like this: RoundMyDouble (double &value, short numberOfPrecisions) It then updates the value with numberOfPrecisions after the decimal
20
4970
by: jacob navia | last post by:
Hi "How can I round a number to x decimal places" ? This question keeps appearing. I would propose the following solution #include <float.h> #include <math.h>
0
7698
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7612
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
6284
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5513
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3640
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1213
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.