Saturday, July 28, 2007

Setting the Number Digits after the Decimal Points in C++ using cout

Without a good book to grasp on how to control the way cout outputs numbers especially floating point numbers could be a misery at times. Here's a brief tips on how to do this:

Fig. 1:

#include // we include iostream since we'll be using cout, since it's definition
// is located in iostream.h file

int main(){
float num = 14.2345; //we directly assign a value to our float num for this example..

cout.setf(ios::showpoint); //this means even if there are no digits after the decimal
// point, just put zeroes

cout.precision(2); //set the number of digits after the decimal point.
cout << "The Number now is " << num << endl; //output the number now..

return 0;
}


That's all.. Try it.. By the way, be reminded that subsequent use of cout once you called
the two lines for setting the number of digits after the decimal points, will be affected, so that means if you have another variable shall we say, myNum and assign it a value of 3.141516
and then you do,

cout << myNum << endl;

it's output will be,

3.14

it will still have the adjustment from the previous settings. So if you don't want it to get affected by the settings for 2-digit decimal point, simply do this,

cout.unsetf(ios::showpoint); //this means reset the original setting of cout's way of outputting
//floating numbers..
cout.precision(0); //

cout << myNum << endl;

the output will be,

3.141516

and it's back to the original setting..

Compared to the printf edition, remember to set the number of digits after the decimal point we simply do something like this,

printf("%0.2f", num);

and everything is set up for us. So in C++ using cout, we'll need to have a bit more toggling before we can set the output for floating numbers according to our needs.

For now, don't mind of those cryptic syntax, the ios::showpoint thing, just stick to the meaning of their purpose first, then once you have a good grasp of the C++, then it's time to be more technical, alright? Trust me, it will save some neurons in your brain.

Take note, this info is for beginners only. So don't flame me you gurus out there.

Till the next tutorials..

3 comments:

Anonymous said...

Nice tutorial! I just found a way to solve my project for setting the number of digits after the decimal point. Thanks!

wired64 said...

maybe you forgot one line, it's,

cout.setf(ios::fixed);

j03m4r13 said...

wired64 thanks for the comment on the tutorial.. Actually if you run the code I posted, it'll work fine, but to be sure most of the time, you can just add the cout.setf(ios::fixed) in every change of the number of digits after the decimal