The following is an example: rounding to two decimal places
<?php $num1 = 21; echo sprintf("%0.2f",$num1)."<br />"; //输出 21.00 $num2 = 16.3287; echo sprintf("%0.2f",$num2)."<br />"; //输出 16.33 $num3 = 32.12329; echo sprintf("%0.2f",$num3)."<br />"; //输出 32.12 ?>
Explain the meaning of %0.2f:
% means the starting character
0 means fill the empty space with 0
2 means there must be two digits after the decimal point
f means convert to floating point number
Convert characters
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
% Print out the percent symbol, Not converted.
b Convert integer to binary.
c Convert the integer into the corresponding ASCII character.
d Convert integer to decimal.
F times precision numbers are converted into floating point numbers.
o Convert integer to octal.
s Convert integers to strings.
x integer is converted to lowercase hexadecimal.
X Convert integer to uppercase hexadecimal.
The difference between printf and sprintf
1. printf function:
int printf ( string format [, mixed args [, mixed ...]] )
Produces output according to format , which is described in the documentation for sprintf() .
Returns the length of the outputted string.
Format the text and then output it, such as:
$name="hunte"; $age=25; printf("my name is %s, age %d", $name, $age);
2. sprintf function:
string sprintf ( string format [, mixed args [, mixed ...]] )
Returns a string produced according to the formatting string format .
Similar to printf, but does not print, but returns formatted text. Others are the same as printf.
3. print function:
is a function that can return a value and can only have one parameter.
int print (string arg)
Outputs arg . Returns 1 , always.