I need to:
- Set precision so that floats are rounded to the hundredths place ( 0.111 prints as 0.11 )
- Clip trailing zeros ( 1.0 prints as 1 )
- Never print an exponent ( 1000.1 prints as 1000.1 )
printf( "%.2f\n", input ); // handles 1 and 3 but not 2
printf( "%.2g\n", input ); // handles 1 and 2 but not 3
cout << setprecision( 2 ) << input << endl; // handles 1 and 2 but not 3
Is there a printf
or cout
option that will let me handle all of these?
The C11 standard says of
%f
and%F
(7.21.6.1:8):Here is a C snippet that produces what you want in a
malloc
ed bloct
, that you need to free up afterwards. If you are writing in C99, a variable-length array can also be considered.The code below does not introduce any additional approximation to the conversion (if your
printf
prints the correctly rounded conversion to decimal, so will the code below), and works for all floating-point values.I am not aware of any format specifier that will do what you are looking for.
Pre-digesting the values before passing them to separate format specifiers might work. For example:
You probably already know this.
I thought another option is to use asprintf() function: it dynamically allocate a string of proper length by itself. Once the string is stored trailing zeros/dot could be cut off:
Sadly there is no way to force streams to use
printf
's%f
behavior. So the only way to handle this is trimming decimal places manually as necessary. I've added a C++ code sample that handles this:fullfloat
will now contain the correct string, but because it's size will extend past the applied'\0'
character the only way to get it to print property would be to usedata()
: