DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, print floating-point number with precision, customise format

When we need to print a number with a specific format, such as printing it as a hexadecimal value or filling it with certain characters in front of it or some formatting options similar to the data format used in GLONASS (Global Navigation Satellite System) NAV DATA etc.
Ex we have some numbers

double a = 100.345;
double b = 2006.008;
double c = 2331.41592653498;
Enter fullscreen mode Exit fullscreen mode

and we can show it look like :

0x64
_______+2006.01
2.331415927E+03
Enter fullscreen mode Exit fullscreen mode

by using functions: setfill, setw, showbase, setprecision...from <iomanip>

cout <<left<<hex<<showbase << nouppercase << (long long)a << endl;
cout <<right<<setfill('_')<<fixed<<setw(15)<<setprecision(2)<<showpos << b << endl;
cout<<left<<scientific<<uppercase<<setprecision(9)<<noshowpos<<c << endl;
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
manishkumar76 profile image
MANISH KUMAR

These are stream manipulators .