Forum Moderators: coopster

Message Too Old, No Replies

Best way to format $vars - using sprintf?

         

neophyte

8:45 am on Oct 1, 2006 (gmt 0)

10+ Year Member



Hello All -

I stumbled across the sprintf function while browsing the PHP manual and have been using it ever since to my great joy.

Where I use to echo currency vars like this:

echo 'US $' , $stdRate , '.00 per room / per night';

Now I just do this:

echo 'US $' , sprintf('%01.2f', $penRate) , ' per-room / per night';

I do the same when I've got to pad month and day numbers with a leading zero before submitting to a db.

Now... I'm wondering ... if sprintf is the "best" way to do this kind of simple formatting chores? Is there another way thats preferred by the good folks here?

Neophyte

PS: in the above notation (%01.2f) what does the "01" do? And is it necessary if all you want is to display 2 places to the right of a decimal?

eelixduppy

5:16 am on Oct 2, 2006 (gmt 0)



You can use number_format [us2.php.net] or money_format [us2.php.net], also.

Ex:


$num = 117;
echo number_format($num,2);
//echos 117.00

As for the format in the sprintf function, it's best explained if you read the documentation [us3.php.net] for that argument.

Good luck!