Home > Backend Development > PHP Tutorial > The difference between sprintf and printf function usage in php, sprintfprintf_PHP tutorial

The difference between sprintf and printf function usage in php, sprintfprintf_PHP tutorial

WBOY
Release: 2016-07-12 09:01:29
Original
1354 people have browsed it

The difference between the usage of sprintf and printf functions in php, sprintfprintf

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 
?>
Copy after login

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);
Copy after login

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/1089038.htmlTechArticleThe difference between the usage of sprintf and printf functions in php, sprintfprintf Here is an example: Rounding to two decimal places?php$ num1 = 21;echo sprintf("%0.2f",$num1)."br /"; //Output 21...
Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template