understanding dollar amount code

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
solidsquirrell
Forum Newbie
Posts: 2
Joined: Mon Sep 28, 2009 7:50 pm

understanding dollar amount code

Post by solidsquirrell »

Hi, im just starting off learning PHP, and stumbled up on this line of code. Any feedback most appreciated.

Dollar amount Code

Code: Select all

$price =25;
$f_price = sprintf("%01.2f",$price);
echo "$fprice";
I understand this code is correct, but Im just having trouble comprehending it.

I would like to know what ("%01 means. (as in what it stands for) I know that ("%01.2f" (highlighted in bold) places an extra " 0 " at the end of 25.000

sorry to ask such a noob question, im currently learning from PHP & MySQL for dummies book.

thx.

S.S.
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: understanding dollar amount code

Post by requinix »

solidsquirrell wrote:I would like to know what ("%01 means. (as in what it stands for) I know that ("%01.2f" (highlighted in bold) places an extra " 0 " at the end of 25.000
Actually, that's not right.

%..f is a placeholder. The 'f' says it's a floating-point number (as opposed to a string or an integer). The "01.2" is the formatting string
- If the first character is a 0 or space then it's to be used as padding
- The rest up to the . is the minimum number of characters (digits) to display, padded with spaces (unless told otherwise) if that minimum can't be met
- The .2 means two digits of precision = two digits to the right of the decimal

There's more explanation on the sprintf manual page.
solidsquirrell
Forum Newbie
Posts: 2
Joined: Mon Sep 28, 2009 7:50 pm

Re: understanding dollar amount code

Post by solidsquirrell »

oh ok, thanks for your input, and the helpful link.
Post Reply