Home > php教程 > php手册 > body text

php的sprintf函数的用法 控制浮点数格式

WBOY
Release: 2016-06-13 09:30:41
Original
1303 people have browsed it

控制浮点数打印格式

浮点数的打印和格式控制是sprintf 的一大常用功能,浮点数使用格式符”%f”控制,默认保留小数点后6 位数字,比如:

复制代码 代码如下:


sprintf("%f", 3.1415926); //结果:"3.141593"

但,有时我们希望自己控制打印的宽度和小数位数,这时就应该使用:”%m.nf”格式,其中m 表示打印数字的整体宽度,n 表示小数点后的位数。比如:

复制代码 代码如下:


sprintf(" %9.3f", 3.1415926); //右对齐:位数不够用空格补全。结果:"    3.142"
sprintf(" %-9.3f", 3.1415926); //左对齐:位数不够用空格补全。结果:"3.142    "
sprintf(" %.3f", 3.1415926); //不指定总宽度,结果:"3.142"

注意一个问题

复制代码 代码如下:


$num = 100;
sprintf("%.2f", $num );
sprintf("%.2f", (double)$num);


上面的两个结果真的一样吗?虽然看起来是一样的,但是下面的原因,可能会有所启发.
原因是:参数压栈时调用者并不知道跟num相对应的格式控制符是个”%f”。而函数执行时函数本身则并不知道当年被压入栈里的是个整数,于是可怜的保存整数$num的那4个字节就被不由分说地强行作为浮点数格式来解释了,整个乱套了。
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 Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!