PHP即时在单位数字前加零 [英] PHP prepend leading zero before single digit number, on-the-fly

查看:106
本文介绍了PHP即时在单位数字前加零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PHP-是否有一种快速的即时测试方法来测试单个字符串,然后在前导零之前添加一个数字?

PHP - Is there a quick, on-the-fly method to test for a single character string, then prepend a leading zero?

示例:

$year = 11;
$month = 4;

$stamp = $year.add_single_zero_if_needed($month);  // Imaginary function

echo $stamp; // 1104

推荐答案

您可以使用sprintf: http://php.net/manual/zh/function.sprintf.php

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

仅在少于所需字符数的情况下才添加零.

It will only add the zero if it's less than the required number of characters.

@FelipeAls指出:

在处理数字时,应使用%d(而不是%s),尤其是在存在负数的情况下.如果您只使用正数,则两个选项都可以正常工作.

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

例如:

sprintf("%04s", 10);返回0010
sprintf("%04s", -10);返回0-10

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

其中:

sprintf("%04d", 10);返回0010
sprintf("%04d", -10);返回-010

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

这篇关于PHP即时在单位数字前加零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆