/* The C way */
#include <stdio.h>
...
float f=12.12123f;
printf("%.2f",f);
// The C++ way
#include <iostream>
...
float f=12.12123f;
std::cout.setf(std::ios_base::fixed, std::ios_base::floatfield);
std::cout.precision(2);
std::cout<<f;
// The alternative C++ way
#include <iostream>
#include <iomanip>
...
float f=12.12123f;
std::cout<<std::fixed<<std::setprecision(2)<<f;
In C, the 0 padding is added automatically to the right if there are not enough digits to print. In the C++ examples, instead, this is disabled; to enable this behavior, you should enable the fixed mode on the stream with std::fixed
(or enabling the relevant stream flags with std::ios_base::setf()
).
Edit: I remembered wrong; if fixed
is not set, the precision
setting says to the stream the total number of digits to display, including also the ones before the decimal point. So, in this case I think that the only way is to use the fixed
mode (examples fixed), which will yield the same behavior of printf
.
Links: