控制浮点数打印格式
浮点数的打印和格式控制是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个字节就被不由分说地强行作为浮点数格式来解释了,整个乱套了。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
