printf

(PHP 4, PHP 5, PHP 7, PHP 8)

printfImprimir una cadena con formato

Descripción

printf(string $format, mixed $args = ?, mixed $... = ?): int

Produce una salida de acuerdo con el format.

Parámetros

format

Vea sprintf() para una descripción de format.

args

...

Valores devueltos

Devuelve la longitud de la cadena impresa.

Ver también

  • print - Mostrar una cadena
  • sprintf() - Devuelve un string formateado
  • vprintf() - Muestra una cadena con formato
  • sscanf() - Interpreta un string de entrada de acuerdo con un formato
  • fscanf() - Analiza la entrada desde un archivo de acuerdo a un formato
  • flush() - Vaciar el búfer de salida del sistema

add a note

User Contributed Notes 4 notes

up
19
dhosek at excite dot com
25 years ago
Be careful:
printf ("(9.95 * 100) = %d \n", (9.95 * 100));

'994'

First %d converts a float to an int by truncation.

Second floats are notorious for tiny little rounding errors.
up
8
php at mole dot gnubb dot net
19 years ago
[Editor's Note: Or just use vprintf...]

If you want to do something like <?php printf('There is a difference between %s and %s', array('good', 'evil')); ?> (this doesn't work) instead of <?php printf('There is a difference between %s and %s', 'good', 'evil'); ?> you can use this function:

<?php
function printf_array($format, $arr)
{
return
call_user_func_array('printf', array_merge((array)$format, $arr));
}
?>

Use it the following way:
<?php
$goodevil
= array('good', 'evil');
printf_array('There is a difference between %s and %s', $goodevil);
?>
and it will print:
There is a difference between good and evil
up
1
deekayen at hotmail dot com
23 years ago
You can use this function to format the decimal places in a number:

$num = 2.12;
printf("%.1f",$num);

prints:

2.1

see also: number_format()
up
-1
simon dot patrick at cantab dot net
6 months ago
A few things to note about printf:
1. The definition of specifier g (or G) is often wrongly stated as being "use e or f (or E or f), whichever results in the shorter string". The correct rule is given in the documentation and it does not always give this result.
2. For g/G/h/H, trailing zeros after the decimal point are removed (but not a zero just after the decimal point, in the e/E style).
3. g/G are locale-aware whether the e/E or f style is produced.
4. For b/o/x/X/u (that is, all integer styles except d) the result shown for negative values is the twos complement form of the number, 2**32 + v, where v is the (negative) value.
To Top