TecBrat
TecBrat

Reputation: 3729

Explanation of this format string used in PHP sprintf

I have been using echo "$".sprintf("%01\$.2f",$numvar); for my USD formatting, but I only copied and pasted that. I looked over the documentation at php.net but it's still not clear to me.

Please help me understand what each part of "%01\$.2f" does in that function.

Upvotes: 2

Views: 1551

Answers (2)

salathe
salathe

Reputation: 51950

  • % is the start of the conversion specification

  • 01\$ signifies that the value will be placed in the first item of the result

    More usually, the same would be written as 1$

  • .2 is the precision specifier, which dictates how many decimal digits should be displayed

  • f means that the argument is treated as a float, and presented as a floating-point number (locale aware)

For full details of the above, and what is available, see the description of the format parameter of sprintf().

Upvotes: 4

citruspi
citruspi

Reputation: 6891

The first argument of the sprint function is the "format". The possible formats include:

Possible format values:

  1. %% - Returns a percent sign
  2. %b - Binary number
  3. %c - The character according to the ASCII value
  4. %d - Signed decimal number
  5. %e - Scientific notation (e.g. 1.2e+2)
  6. %u - Unsigned decimal number
  7. %f - Floating-point number (local settings aware)
  8. %F - Floating-point number (not local settings aware)
  9. %o - Octal number
  10. %s - String
  11. %x - Hexadecimal number (lowercase letters)
  12. %X - Hexadecimal number (uppercase letters)

Additional format values. These are placed between the % and the letter (example %.2f):

  1. "+" (Forces both + and - in front of numbers. By default, only negative numbers are marked)
  2. ' (Specifies what to use as padding. Default is space. Must be used together with the width specifier. Example: %'x20s (this uses "x" as padding)
  3. "-" (Left-justifies the variable value)
  4. [0-9] (Specifies the minimum width held of to the variable value)
  5. .[0-9] (Specifies the number of decimal digits or maximum string length)

Upvotes: 1

Related Questions