Printing float values ​​with sprintf

Now I have:

printf('Rating: %.2F', $rating);

which prints like:

4.00

How can I show the initial zero only if there is something to show after it?

For instance:

  • 4.00 should be 4
  • 4.20 should be 4.2
  • 4.02 should be 4.02 :)
+4
source share
1 answer
 printf("Rating: %g\n", 4.00); printf("Rating: %g\n", 4.20); printf("Rating: %g\n", 4.02); 

prints

 Rating: 4 Rating: 4.2 Rating: 4.02 

This way values ​​without printf will be printed

demo

+9
source

Source: https://habr.com/ru/post/1382181/


All Articles