Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up C++ Number Formatting to a certain precision?

I understand that you can use iomanip to set a precision flags for floats (e.g. have 2.0000 as opposed to 2.00).

Is there a way possible to do this, for integers?

I would like a hex number to display as 000e8a00 rather than just e8a00 or 00000000 rather than 0.

Is this possible in C++, using the standard libraries?

like image 430
Anthony Avatar asked Feb 24 '10 15:02

Anthony


People also ask

How do I specify precision in printf?

The printf precision specifiers set the maximum number of characters (or minimum number of integer digits) to print. A printf precision specification always begins with a period (.) to separate it from any preceding width specifier.

How do you change the precision of a number?

By using the setprecision function, we can get the desired precise value of a floating-point or a double value by providing the exact number of decimal places. If an argument n is passed to the setprecision() function, then it will give n significant digits of the number without losing any information.

How do I print 2 digits after a decimal?

we now see that the format specifier "%. 2f" tells the printf method to print a floating point value (the double, x, in this case) with 2 decimal places. Similarly, had we used "%. 3f", x would have been printed rounded to 3 decimal places.


1 Answers

With manipulators:

std::cout << std::setfill('0') << std::setw(8) << std::hex << 0 << std::endl;

Without manipulators:

std::cout.fill('0');
std::cout.width(8);
std::cout.setf(std::ios::hex, std::ios::basefield);
std::cout << 42 << std::endl;
like image 175
Nick Meyer Avatar answered Sep 25 '22 00:09

Nick Meyer