Can I make printf format floats like C++ streams
Asked Answered
D

1

6

I am comparing the output of two programs, one C the other C++, using diff, so the output must be identical.

Is there any way to printf a double so that it is formatted as though it was printed using << mydouble.

I am currently using printf("%g",mydouble)

Here are some examples of the differences:

c: 3.24769e-05 c++: 3.2477e-05
c: 0.0026572   c++: 0.00265721

Interestingly the scientific notation has more digits in c, and the decimal notation has more in c++.

Demetriusdemeyer answered 13/1, 2014 at 6:12 Comment(2)
Using printf in the C++ might be easier.Receptor
Which part of the manual do you have a question about?Tem
W
3

You can solve this by using the format specifiers in C.

For example, say you would like to print out only 3 places after the decimal, you could make your printf like so:

printf("%.3lf", dub);

With a value of double dub = .0137; the output would be 0.014

This would fix the issue with your 2nd case if you want more precision printed you could write:

printf("%.8lf", dub);

Your output for double dub = 0.00265721; would then be 0.00265721

The case for %g works the same way except the number on the left is included in the calculation. If you wanted the C++ version (the lesser precision I assume) then your code would look like this:

double dub = .0000324769;
printf("%.5g", dub);

Which yields 3.2477e-05

Wilbertwilborn answered 13/1, 2014 at 6:59 Comment(2)
On my system at least, changing %g to %.5g makes the output decimal instead of scientific for certain values.Demetriusdemeyer
oh okay .4 is what i needed -- duhDemetriusdemeyer

© 2022 - 2024 — McMap. All rights reserved.