Thursday, August 6, 2009

Echo, print, printf, sprintf

I just spent 20 minutes trying to figure out why my formatted number wasn't looking correct. I printf("%5.2f%%", 3.123) and was getting 3.12%1.

This is one of those mistakes that drives me nuts.

The code was actually
<?php echo printf("%.1f",($user_statistics['Active Users']['value']/$user_statistics['users_allowed']*100));?>

printf returns "true" or 1 when it finishes.

I made this mistake because originally the code was --

<?php echo $user_statistics['users_allowed'];?>

The solution?

1. Get rid of the echo OR
2. Use sprintf instead of printf and leave the echo.

Considering the PHP manual refers you to sprintf when you look at printf, I guess sprintf might be more common.

Doesn't really matter which way you go, just recognize which way you are going.