Heim  >  Artikel  >  Backend-Entwicklung  >  php中sprintf与printf函数用法区别,sprintfprintf_PHP教程

php中sprintf与printf函数用法区别,sprintfprintf_PHP教程

WBOY
WBOYOriginal
2016-07-12 09:01:291275Durchsuche

php中sprintf与printf函数用法区别,sprintfprintf

下面是一个示例:四舍五入保留小数点后两位

<?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 
?>

解释下 %0.2f 的含义:

% 表示起始字符
0 表示空位用0填满
2 表示小数点后必须占两位
f 表示转换成浮点数


转换字符
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
% 印出百分比符号,不转换。 
b 整数转成二进位。 
c 整数转成对应的 ASCII 字元。 
d 整数转成十进位。 
f 倍精确度数字转成浮点数。 
o 整数转成八进位。 
s 整数转成字串。 
x 整数转成小写十六进位。 
X 整数转成大写十六进位。

printf与sprintf的区别

1. printf函数:

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.

 

把文字格式化以后输出,如:

$name="hunte"; 
$age=25; 
printf("my name is %s, age %d", $name, $age);

2. sprintf函数: 
string sprintf ( string format [, mixed args [, mixed ...]] )

Returns a string produced according to the formatting string format .

 

跟printf相似,但不打印,而是返回格式化后的文字,其他的与printf一样。


3. print函数:

是函数,可以返回一个值,只能有一个参数。

int print ( string arg )

Outputs arg . Returns 1 , always.

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1089038.htmlTechArticlephp中sprintf与printf函数用法区别,sprintfprintf 下面是一个示例:四舍五入保留小数点后两位 ?php$num1 = 21;echo sprintf("%0.2f",$num1)."br /"; //输出 21...
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn