简体   繁体   中英

Adding both leading and trailing zeros before/after any number in PHP

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

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

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

$num_padded = sprintf("%02.2f", $num);

因此,我们在该点之后有2位数字,在该点之前有2位数字(可能是零)。

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

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