简体   繁体   中英

How do I format a numeric value in php?

I have to print a numeric value which is less than 10 in the following format:

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

Are there any php library functions which will format numbers in this way?

Use printf or sprintf :

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

See it in action .

The sprintf page also documents the syntax for formatting specifiers ( %02d ), so you can also see what other options are available.

printf('%02u', $number)

http://php.net/sprintf

Use str_pad function.

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

PHP Manual - str-pad

You can check if the value is less than ten and concatenate using the dot operator '.', ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM