1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Handling Ints and Floats

By David Bolton, About.com

5 of 8

Specifying Output Formats with cout

When you're outputting numbers, you need to think about these attributes of the numbers.
  • Width- How much space is needed for the entire number
  • Alignment - left or right- numbers tend to be right aligned
  • Number of decimal places
  • Sign or brackets for negative numbers.
  • Thousands Separators. Big numbers look ugly without these.
Now width, alignment, number of decimal places and signs can be set by the cout object and iomanip include file functions.

Thousands separators are a little more complicated. They are set from the locale of a PC. A locale contains information relevant to your country- such as currency symbols and decimal point and thousands separators. In the UK and USA, the number 100.98 uses a decimal point . as the decimal point whereas in some European countries it is a comma so €5,70 means a price of 5 Euros and 70 cents.

int main()
{
double a=925678.8750;
cout.setf(ios_base::showpoint|ios_base::right) ;
cout.fill('=') ;
cout.width(20) ;
locale loc("") ;
cout.imbue( loc ) ;
cout.precision(12) ;
cout << "The value is " << a << endl;

//cout.unsetf(ios_base::showpoint) ;
cout << left << "The value is " << a << endl;

for (int i=5;i< 12;i++) {
cout.precision(i) ;
cout << setprecision(i)<< "A= " << a << endl;
}

const moneypunct <char, true> &mpunct = use_facet <moneypunct <char, true > >(loc) ;

cout << loc.name( )<< mpunct.thousands_sep( ) << endl;
return 0;
}
The output from this is
=======The value is 925,678.875000
The value is 925,678.875000
A= 9.2568e+005
A= 925,679.
A= 925,678.9
A= 925,678.88
A= 925,678.875
A= 925,678.8750
A= 925,678.87500
English_United Kingdom.1252,

On the Next Page More about Locale

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Specifying Output Formats

©2009 About.com, a part of The New York Times Company.

All rights reserved.