-
decimal places
//intarith.cpp//
//convert cents to dollars and cents//
I am trying to print the result with two decimal places but it is not working.
I get a result of 1234.6 but i want 1234.06 the 0 does not print
Help!
#include <iostream.h>
#include <iomanip.h>
#define cents_per_dollars 100 //cents in dollars//
int main (void)
{
long cents;
long d, c;
cents=123406;
d=cents/cents_per_dollars;
c=cents%cents_per_dollars;
cout.setf(ios::fixed,ios::floatfield);
cout<<setprecision(2)<<"123406 cents= "<<"$"<<d<<"."<<c<<"\n";
return 0;
}
-
io formatting
that is because you are working with long integers and float variables...
-
Change your cout statement to this:
cout<<setprecision(2)<<"123406 cents= "<<"$"<<d<<".";
if(c < 10)
cout<<"0";
cout<<c<<"\n";
You must print the leading 0s yourself.
-
have a look at the second last post on this page
-
Try this:
Code:
cout.setf(ios::fixed,ios::floatfield);
cout.width(2);
cout << setprecision(2) << "123406 cents= " << "$" << d << ".";
cout.width(2);
cout << setfill('0') << c << endl;
-
With respect to Cshot and Swoopy, an alternative (not better, just an alternative) method:
Code:
#include <iostream>
#include <iomanip>
#include <conio.h>
#define cents_per_dollars 100 //cents in a dollar
int main (void)
{
long cents;
long d, c;
int fillFlag = 0;
cents = 123406;
d = cents / cents_per_dollars;
c = cents % cents_per_dollars;
if (c < 10)
fillFlag = 1;
std::cout << cents << " cents = " << "$" << d << ".";
if (fillFlag)
std::cout << std::setw(2) << std::setfill('0') << c << '\n';
else
std::cout << c << '\n';
getch();
return 0;
}
The only real advantage? You can change the value of 'cents' without the hardcode restriction in the 'std::cout' statement.
(Please...no, stop...you're all far too kind...:D )
-Skipper