C++ Format Specifiers
In this page:
Floating-Point Formatting
The fixed stream manipulator forces floating-point numbers to print in standard decimal notation rather than switching to scientific notation for very large or small values. Combine it with setprecision to control exactly how many digits appear after the decimal point, which is essential for anything like displaying money.
Example: Floating-Point Formatting
#include <iostream>
#include <iomanip>
int main() {
double price = 19.5;
std::cout << std::fixed << std::setprecision(2) << price << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Hexadecimal and Octal Formats
The hex and oct manipulators switch how subsequent integers print — hex shows them in base-16 and oct in base-8 — while dec switches back to the normal base-10 you'd expect. These are especially useful when debugging low-level code, where seeing a value's hexadecimal form makes bit patterns and memory addresses much easier to read.
Example: Hexadecimal and Octal Formats
#include <iostream>
int main() {
int value = 255;
std::cout << std::hex << value << std::endl;
std::cout << std::oct << value << std::endl;
std::cout << std::dec << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Boolean Output Format
By default C++ prints boolean values as the raw integers 1 and 0, which can be confusing in output meant for a human reader. Applying boolalpha makes cout print the actual words true and false instead, and noboolalpha switches back to the numeric form if you need it again later.
Example: Boolean Output Format
#include <iostream>
int main() {
bool active = true;
std::cout << active << std::endl; // 1
std::cout << std::boolalpha << active << std::endl; // true
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Scientific Notation
scientific formats floating-point numbers using exponential notation, like 1.5e+08 instead of 150000000, which keeps very large or very small numbers compact and easy to compare at a glance. This matters in scientific or engineering code where values can span many orders of magnitude in the same output.
Example: Scientific Notation
#include <iostream>
int main() {
double bigNumber = 150000000.0;
std::cout << std::scientific << bigNumber << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Base Prefix Formatting
showbase adds a visible prefix that identifies a number's base — 0x for hexadecimal and a leading 0 for octal — so a reader doesn't have to guess how to interpret the digits that follow. It's most useful alongside hex or oct, since without it a hex value like ff could easily be mistaken for decimal.
Example: Base Prefix Formatting
#include <iostream>
int main() {
int value = 255;
std::cout << std::showbase << std::hex << value << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: