Question

What single format string can be used to print 0.0, 1.0, 0.025 ? eg given:

float vals[3] = { 0.0f, 1f, 0.025f };

for(int i=0; i < 3; i++)
    printf("%g\n", vals[i]);

desired output:

0.0
1.0
0.025

but instead get:

0
1
0.025

Have tried various width specifiers and %f vs %g but can't get what I want.

If there's a c++ alternative that's fine to.

Was it helpful?

Solution

You can use * to tell printf the precision will come from an int argument value.

printf("%.*f\n", (vals[i] == (int)vals[i]) ? 1 : 3 ,vals[i]);

should print:

0.0
1.0
0.025

OTHER TIPS

You can specify the precision following the decimal place for floating point numbers and doubles when you print it. This is done with a format specifier like: %.Nf where N is a positive integer. So if you used:

printf("%.3f\n", vals[i]);

Your output is:

0.000
1.000
0.025

But you can't get it to print it exactly the way you declared it. You would have to change the precision at different stages of the loop (%.1f for the first 2 iterations and then %.3f for the last iteration). There are a lot of options for printf including leading spaces as well:

http://pubs.opengroup.org/onlinepubs/009695399/functions/printf.html

edit:

So if you want to have a minimum of 1 decimal place printed as you explained in your comment you can add an explicit check for that one case:

#include <math.h>
#include <stdio.h>

int 
main(int argc, char *argv[]) {
  float vals[3] = { 0.0f, 1.0f, 0.025f };

  for(int i=0; i < 3; i++) {
    if( fmod(vals[i],1) == 0) printf("%.1f\n", vals[i]);
    else printf("%f\n", vals[i]);
  }

  return 1;
}

Output:

0.0
1.0
0.025000

You can use setprecision(int n), where n is the number of decimal places to output. Any trailing zeros will not be shown unless you use fixed notation

#include <iostream>
#include <iomanip>

float vals[3] = { 0.0f, 1.0f, 0.025f };
std::cout << setprecision(5);
for(int i=0; i < 3; i++)
std::cout << vals[i];

Output

0.0
1.0
0.025

Change the following for fixed notation

cout << setprecision(5) << fixed;

Output

0.00000
1.00000
0.02500

edit: There is also scientific notation, you can figure out what that does. setprecision() ---> std::setprecision()

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top