如何在php中格式化数值?

时间:2011-10-27 14:15:06

标签: php

我必须按以下格式打印小于10的数值:

for 0 I want to print it 00
for 1 I want to print it 01
for 2 I want to print it 02

是否有以这种方式格式化数字的php库函数?

4 个答案:

答案 0 :(得分:5)

使用printfsprintf

$i = 1;
printf('%02d', $i);

<强> See it in action

sprintf页面还记录了格式说明符(%02d)的语法,因此您还可以查看其他可用选项。

答案 1 :(得分:2)

printf('%02u', $number)

http://php.net/sprintf

答案 2 :(得分:2)

使用str_pad函数。

str_pad($number_str,2,'0',STR_PAD_LEFT)

PHP Manual - str-pad

答案 3 :(得分:0)

您可以检查该值是否小于10并使用点运算符“。”连接,即

if($i < 10 && $i >0) print '0'.$i;
else print $i;