Home  >  Article  >  Backend Development  >  php中sprintf与printf函数用法差别

php中sprintf与printf函数用法差别

WBOY
WBOYOriginal
2016-06-13 12:28:21815browse

php中sprintf与printf函数用法区别

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

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

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