php的sprintf函数的用法 控制浮点数格式_php实例
May 17, 2016 am 08:49 AM控制浮点数打印格式
浮点数的打印和格式控制是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个字节就被不由分说地强行作为浮点数格式来解释了,整个乱套了。
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

Hot Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot tools Tags

Hot Article
Repo: How To Revive Teammates
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
How Long Does It Take To Beat Split Fiction?
3 weeks ago
By DDD
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago
By 尊渡假赌尊渡假赌尊渡假赌

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

11 Best PHP URL Shortener Scripts (Free and Premium)

Working with Flash Session Data in Laravel

Build a React App With a Laravel Back End: Part 2, React

Simplified HTTP Response Mocking in Laravel Tests

cURL in PHP: How to Use the PHP cURL Extension in REST APIs

12 Best PHP Chat Scripts on CodeCanyon
