简体   繁体   中英

PHP How do I format a number to show the hundreds as zero if the number is less than 100?

I'm calculating a countdown to a date. XXX Days Left. I'd like to show the hundreds place as zero if the total days left is less than 100.

This is where I'm at so far:

$now = time();
$your_date = strtotime(get_field('first_day'));
$datediff = abs($now - $your_date);
echo floor($datediff/(60*60*24));

Based on the target date, the output is 72. I'd like it to show 072.

Can someone help me with this?

You can use str_pad()

echo str_pad($value, 3, "0", STR_PAD_LEFT);

Or sprintf()

echo sprintf("%03d", $value);

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