Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing float values with sprintf

Right now I have:

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

which prints like:

4.00

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

For example:

  • 4.00 should be 4
  • 4.20 should be 4.2
  • 4.02 should be 4.02 :)
like image 636
Alex Avatar asked Nov 20 '11 21:11

Alex


1 Answers

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

So will printing the values without printf

demo

like image 87
Gordon Avatar answered Oct 19 '22 09:10

Gordon