2

I have these two numbers which are 4 and 4.5. i want both of it to be formatted as 04 and 04.50.

below is what i have done to display number 4 correctly.

$num_padded = sprintf("%02s", 4);
echo $num_padded;

but it doesn't work for 4.5

also if the no is 2 digit like 10 or 10.50 then no zero should be added. when value is 10.5 last zero must be added. how can i get a similar work done with PHP?

i found a similar answer here but not exactly what i am looking for. PHP prepend leading zero before single digit number, on-the-fly

4

5 回答 5

2

一种方法是如果您的号码在 [0, 10) 范围内,只需在前面加上“0”

$num_padded = $num;
if ($num != floor($num)) {
    $num_padded = sprintf("%2.2f", $num);
}

if ($num < 10 && $num >= 0)
   $num_padded = "0" . $num_padded;
于 2013-09-30T16:03:14.400 回答
1

也许这可能是一个解决方案;它满足所有评论案例:

$num = 10.5;
$padded="0000".$num."0000";
if (($dotpos = strpos($padded, ".")) !== FALSE) {
    $result = substr($padded, $dotpos-2, 2).".".substr($padded, $dotpos+1, 2);
} else {
    $result = sprintf("%02s", $num);
}
echo $result;

案例:

数字 = 4 -> 输出 = 04

数字 = 4.5 -> 输出 = 04.50

数字 = 10 -> 输出 = 10

数量 = 10.5 -> 输出 = 10.50

于 2013-09-30T16:12:32.820 回答
1

我自己写了这个函数。

function format_string($str) {    
   $val = '';
   if (is_int($str))  
     $val = sprintf("%02s", $str);  
   else if (is_float($str))
     $val = str_pad(sprintf("%0.2f", $str), 5, '0', STR_PAD_LEFT);  
  return $val;    
}

echo format_string(4); // 04
echo format_string(4.5); // 4.50
于 2013-09-30T16:07:47.557 回答
0
$num_padded = sprintf("%02.2f", $num);

所以我们在点之后有 2 位数字,在之前有两位数字(可能是零)。

于 2013-09-30T16:15:29.797 回答
0

这正是您需要的:

str_pad( )

字符串 str_pad( 字符串 $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

参考: http: //php.net/manual/en/function.str-pad.php

参数:

  1. 你的号码
  2. 你想要多少个空格(或 0)
  3. 替换这些空格的字符(第 3 项)
  4. 数字的左边或右边(字符串,第一个参数)

例子:

echo str_pad( '9', 10, '0', STR_PAD_LEFT ); // 0000000009
echo str_pad( '9', 10, '0', STR_PAD_RIGHT ); // 9000000000

对不起我的英语不好

于 2013-09-30T16:39:36.943 回答