Home  >  Article  >  Backend Development  >  Analysis of the difference between sprintf and printf function usage in php_PHP tutorial

Analysis of the difference between sprintf and printf function usage in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:25:07771browse

Here is an example: round to two decimal places

Copy code The code is as follows:

$num1 = 21;
echo sprintf( "%0.2f",$num1)."
"; //Output 21.00
$num2 = 16.3287;
echo sprintf("%0.2f",$num2)."< br />"; //Output 16.33
$num3 = 32.12329;
echo sprintf("%0.2f",$num3)."
"; //Output 32.12
?>

Explain the meaning of %0.2f:

% means the starting character
0 means fill the 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 integer to 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 lower case 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:

Copy code The code is as follows:

$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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/825226.htmlTechArticleThe following is an example: rounding to two decimal places. Copy the code. The code is as follows: ?php $num1 = 21; echo sprintf("%0.2f",$num1)."br /"; //Output 21.00 $num2 = 16.3287; echo sp...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn