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.
(PHP 4, PHP 5, PHP 7, PHP 8)
printf — Imprimir una cadena con formato
Produce una salida de acuerdo con el format
.
Devuelve la longitud de la cadena impresa.
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.
[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
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()
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.