Skip to the content of the web site.

Formatted printing of floating-point numbers in C++

Author: Douglas Wilhelm Harder

As a user, you can print an integer as either base 16 (hexadecimal), base 8 (octal) or base 2 (binary) using existing output manipulators and the std::bitset data structure:

#include <iostream>
#include <bitset>

int main() {
	// Print an integer in hexadecimal, octal and binary
	std::cout << std::hex << 42 << std::endl;
	std::cout << std::oct << 42 << std::endl;
	std::cout << std::bitset<32>( 42 ) << std::endl;

	return 0;
}

You can execute this code at cpp.sh.

If you try this with floating-point numbers, it doesn't work as you may expect; instead, the first two simply print the decimal representation.

The float_rep library allows the user to print floating-point numbers using the C++ output streams. The output manipulators only work on the immediate following operand, and if that is not a floating-point type, it is printed out as per normal.

For example, to print 42.3134765625 as a double, we would use this program:

#include <iostream>
#include "float_rep.h"

int main() {
	// Print a 'double' in hexadecimal, octal and binary
	double x{ 42.3134765625 };
	std::cout << x << std::endl;
	std::cout << ece204::hex << x << std::endl;
	std::cout << ece204::oct << x << std::endl;
	std::cout << ece204::bin << x << std::endl;

	return 0;
}

The output is

42.3135
4045282000000000
2004|245010000000000000
0|10000000100|0101001010000010000000000000000000000000000000000000

To print -42.3134765625 as a float, we would use this program:

#include <iostream>
#include "float_rep.h"

int main() {
	// Print a 'float' in hexadecimal, octal and binary
	float x{ -42.3134765625 };
	std::cout << x << std::endl;
	std::cout << ece204::hex << x << std::endl;
	std::cout << ece204::oct << x << std::endl;
	std::cout << ece204::bin << x << std::endl;

	return 0;
}

The output is

-42.3135
c2294100
604|24501000
1|10000100|01010010100000100000000

To print π as a long double, we would use this program:

#include <iostream>
#include "float_rep.h"

int main() {
	// Print a 'long double' in hexadecimal and binary
	long double x{ 3.1415926535897932385L };
	std::cout << x << std::endl;
	std::cout << ece204::hex << x << std::endl;
	// Printing a 'long double' in octal is not implemented...
	std::cout << ece204::bin << x << std::endl;

	return 0;
}

The output is

3.14159
4000c90fdaa22168c235
0|100000000000000|1.100100100001111110110101010001000100001011010001100001000110101