In php the usage of sprintf and printf functions is analyzed
- 2021-01-02 21:47:09
- OfStack
Here's an example: 4 rounded to 5 to keep two decimal places
<?php
$num1 = 21;
echo sprintf("%0.2f",$num1)."<br />"; // The output 21.00
$num2 = 16.3287;
echo sprintf("%0.2f",$num2)."<br />"; // The output 16.33
$num3 = 32.12329;
echo sprintf("%0.2f",$num3)."<br />"; // The output 32.12
?>
Explain what %0.2f means:
% represents the start character
Zero means the empty space is filled with zero
Two means you have to have two decimal places
f represents converting to floating-point numbers
The conversion character
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
% prints out the percentage symbol and does not convert.
b integers are rounded to 2.
The c integer is converted to the corresponding ASCII character.
d integers are rounded to 10.
f times precision to convert numbers to floating point numbers.
o integers turn into 8 carries.
s integer converted into a string.
The x integer is carried in lowercase 106.
X integers are carried in capital 106.
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 for output, 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 not printed, but returns formatted text, the rest as printf1.
3. print function:
Is a function that returns 1 value and has only 1 argument.
int print ( string arg )
Outputs arg . Returns 1 , always.