PHP - String Format Type Specifiers

Introduction

The d within the conversion specification, "%d", is called a type specifier.

It tells printf() to format the argument as a decimal integer.

You can format in other ways using different type specifiers, as follows:

Type SpecifierMeaning
b Treat the argument as an integer and format it as a binary number.
c Treat the argument as an integer and format it as a character with that ASCII value.
d Treat the argument as an integer and format it as a signed decimal number.
e Format the argument in scientific notation (for example, 3.45e+2).
f Format the argument as a floating-point number, taking into account the current locale settings.
F Format the argument as a floating-point number, ignoring the locale settings.
o Treat the argument as an integer and format it as an octal number.
s Format the argument as a string.
u Treat the argument as an integer and format it as an unsigned decimal number.
x Treat the argument as an integer and format it as a lowercase hexadecimal number.
X Treat the argument as an integer and format it as an uppercase hexadecimal number.
% Display a literal percent (%) symbol. This doesn't require an argument.

Here's an example script that displays the same argument-the number 123.45- formatted using different type specifiers:

Demo

<?php
         $myNumber = 123.45;/*from   w w w  .j ava 2s  .com*/
         printf("Binary: %b \n ", $myNumber );
         printf("Character: %c \n ", $myNumber );
         printf("Decimal: %d \n ", $myNumber );
         printf("Scientific: %e \n ", $myNumber );
         printf("Float: %f \n ", $myNumber );
         printf("Octal: %o \n ", $myNumber );
         printf("String: %s \n ", $myNumber );
         printf("Hex (lower case): %x \n ", $myNumber );
         printf("Hex (upper case): %X \n ", $myNumber );
?>

Result

Related Topic