Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Formating a float

Status
Not open for further replies.

sheila11

Programmer
Dec 27, 2000
251
0
0
US
Hi all,

I get a float value as an output that varies is number of digits. I need to output a fixed number of digits only. How can I format it?

TIA,
Sheila
 
If you can use printf to output formated variable values to the standard output stream.

Example:
================

double dNum;
dNum = 123456.7890123

printf( "Real numbers:\n\t%f %.2f %e %E\n", dNum, dNum, dNum, dNum );

=====================
note: "%.2f" - formats a floating point number with two digits to the right of the decimal place.

You can get specifics on formating from the MSDN Library, just search on "Format Specification Fields: printf and wprintf Functions"


 
When using C++ output stream:

#include <iostream>
#include <iomanip>

using namespace std;

float x = 9.283746372;
cout << setiosflags(ios::fixed) << setprecision(2) << x << endl;


9.28
 
#include<iomanip>


cout<<setprecision(3)<<setiosflags(ios::fixed);

Note: When the ios::fixed flag is set, the value specified by the setprecision manipulator will be the number of digits to apper after the decimal point, not the number of significant digits.
Hope this will help you!!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top