Question

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

Was it helpful?

Solution 2

Maybe this could be a solution; it satisfies all commented cases:

$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;

Cases:

num = 4 -> output = 04

num = 4.5 -> output = 04.50

num = 10 -> output = 10

num = 10.5 -> output = 10.50

OTHER TIPS

One way to do this is by simply prepending a "0" if your number is in the [0, 10) range

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

if ($num < 10 && $num >= 0)
   $num_padded = "0" . $num_padded;

I wrote this function on my own.

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
$num_padded = sprintf("%02.2f", $num);

So we have 2 digits after the point, and two digits (maybe zeros) before.

This is exactly what you need:

str_pad( )

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

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

Parameters:

  1. your number
  2. how many spaces (or 0) you want
  3. a character to replace these spaces (item 3)
  4. the left or right of the number (string, first parameter)

Example:

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

Sorry for my english

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top