php 如何计算php中包含零的位数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17037255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count number of digit included zero in php
提问by Kevin
I am working to count number of digit in PHP. I just want to count number of digit value for database.In first number have zero means , it won't take as a number for counting.
我正在计算 PHP 中的位数。我只想计算数据库的位数。在第一个数字为零的情况下,它不会作为计数的数字。
for example:
例如:
12 ==number of count value is 2
122 ==number of count value is 3
I can achieve this through function.here my function.
我可以通过function.here我的功能来实现这一点。
function count_digit($number)
{
return strlen((string) $number);
}
$number = 12312;
echo count_digit($number); // 5
But I need to add zero for that number $num = 0012312;
(zero-fill).
但我需要为该数字添加零$num = 0012312;
(零填充)。
012 == number of count value is 3
0133 == number of count value is 4
Let me know how to solve it.
让我知道如何解决它。
回答by Kevin
If you wish the leading zeros to be counted too, you should assign it as a string and not as number.
如果您也希望对前导零进行计数,则应将其指定为字符串而不是数字。
Then, try to calculate the number of characters. This time, it will include the zeros. No need to type cast inside the function.
然后,尝试计算字符数。这一次,它将包括零。无需在函数内输入类型转换。
So, now your code will look like this:
所以,现在你的代码看起来像这样:
function count_digit($number) {
return strlen($number);
}
//function call
$num = "number here";
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
//prints 5
回答by Ganesh Kanawade
function count_digit($number) {
return strlen((string) $number);
}
//function call
$num = "012312";
$number_of_digits = count_digit($num); //this is call :)
echo $number_of_digits;
Make $num variable as a string.
将 $num 变量设为字符串。
回答by Blue Water
There is no need for a function wrapper. The answer is
不需要函数包装器。答案是
$n = "00001";
mb_strlen((string) $n); // result is 5