Rounding off the number (money) and showing

Hi I'm a begginer of C++ and I have been trying to make my program to round off the number for money. For example $12.65515 then it will become $12.66 and $0.01 will be round off. I don't know how to do that I have been searching everywhere and I couldn't find it. Another thing is i want my program to show if the money have been round up/off like Total $12.66, Rounding -$0.01. Thank for your help.
here is a good article on rounding numbers and examples:

http://www.cplusplus.com/forum/articles/3638/
yeah that is a good example thanks for that but i dont think it would work in my case
here is a link to setprecision which should help:
http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
1
2
3
4
5

    cout << fixed << setprecision(2); // this will change every float number in your program 
    
    cout << 12.45343 << endl;


or you can do this

1
2
3
    
    cout << fixed << setprecision(2) << 12.45632 << endl; // or you can do it this way and it will only change the float number on this line
yeap the 1st problem is solved but what about showing the number that round off/up ?? like

Amount $15.11
Rounding -$0.01
Total $15.10

???????
This works but I'm not sure if this is what your looking for
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main( )
{
    double moneyAmountOne;
    double roundDown;

    cout << fixed << setprecision(2);

    cin >> moneyAmountOne;

    roundDown = moneyAmountOne - 0.01;

    cout << roundDown << endl;

    return( 0 );
}



if you wanted to find the difference of the rounded number and original you'd want to use a std::stringstream, that way you can set the precision push the number in and then read it out again into a second float value. then you can take the numeric difference and cout all 3 values...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <sstream>
#include <iostream>
#include <cmath>
#include <iomanip>

using namespace std;

int main( ){
    double inputAmount, difference, roundedAmount;

    stringstream sstream;
    
    cin >> inputAmount;

    sstream << fixed << setprecision(2);
    sstream << inputAmount << flush;
    sstream >> roundedAmount;
    sstream << roundedAmount - inputAmount << flush;
    sstream >> difference;

    cout << inputAmount << endl << difference << endl << roundedAmount << endl;

    return 0;
}


I'm not 100% sure stringstreams support precision but I'm pretty sure it's a stream universal ability. Also I don't off the top of my head know the call to force the stringstream to clear its contents if any, but you'd want to put that between lines 17 and 18.
Never seen the sstream do you have a link I can check out to learn more?

Thanks in advance
Topic archived. No new replies allowed.