Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Formatting Floating Point Numbers

Floating point numbers tend to make the most mess in your output. The preceding example wasn't exactly clean: The numbers didn't line up, and the second line has each number taking up a different amount of space, even though I wrote each floating point number with the same level of precision.

Let's fix that problem with the 1. I want a decimal point and some zeros. Add this block of code to the end of your main function:

  cout << "Take 3" << endl;
  cout << showpoint;
  cout << x << " " << y << " " << z << endl;
  cout << p << " " << q << " " << r << endl;
  cout << endl;

This code uses a manipulator called showpoint that tells the stream to go ahead and show the decimal point and some zeros with whole numbers. Here's the output from this block of code:

Take 3
100 20 5
3.14 0.333 1.00

That looks a little bit better. Now the physicists down the hall will be glad to know we didn't just round to the closest whole number.

Incidentally, you might be curious about what a manipulator is. You can think of a manipulator as an object that you shove into the stream to modify the behavior of the stream (as is the case with the showpoint manipulator) or to cause some particular character or set of characters to be written to the stream (as is the case with the endl manipulator). But believe it or not, a manipulator is really a function. It's true. Deep down inside the bowels of the C++ library lives a function called showpoint and a function called endl. But the C++ library also includes a special version of the << operator that looks specifically for functions of a certain prototype. If the library sees such a function, it will actually call the function, passing to the function the stream. Thus, when you have a line like this, you will really be calling endl(cout):

cout << endl;

You can try this out for yourself with code such as this:

cout << "a";
cout << "b";  

Of course, your colleagues wouldn't be thrilled with you for writing code that's so nonstandard, so most people prefer the simpler version:

cout << "a" << endl << endl << endl << "b";

That's how manipulators work.

Back to the formatting issue, the C++ library includes numerous formatting manipulators that tell a stream how to format your floating point numbers and other text. Personally, I'm still not quite satisfied with the look of the output from the Take 3 example. I'd like to have everything lined up. Let's tackle that next.

  • + Share This
  • 🔖 Save To Your Account