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 .

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay