Possible Duplicate:
Format number in PHP
I want my number format 12 char in length
, like if there is value 12
it should output 000000000012
Example: if value is 123.50
it should output 000000012350
No decimal (multiple of 100)
Any idea, which function will be used?
Thanks !
You can use str_pad
echo str_pad(12, 12, "0", STR_PAD_LEFT);
You can also use printf or sprintf
printf("%012s", 12);
Output
000000000012
Some Work Arounds
var_dump(formatOutput("12"));
var_dump(formatOutput("123.50"));
var_dump(formatOutput("123.378201"));
function formatOutput($no,$max = 15) {
$no = str_pad("1", strlen(substr(strrchr($no, "."), 1)), "0", STR_PAD_RIGHT) * $no;
if(strpos($no, "."))
$no = str_replace(".", "", $no) . "0" ;
return str_pad($no, $max, "0", STR_PAD_LEFT);
}
Output
string '000000000000012' (length=15)
string '000000000001235' (length=15)
string '000001233782010' (length=15)
See str_pad()
http://php.net/manual/en/function.str-pad.php
string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )
This functions returns the input string padded on the left, the right, or both sides to the specified padding length. If the optional argument pad_string is not supplied, the input is padded with spaces, otherwise it is padded with characters from pad_string up to the limit.
input
The input string.
pad_length
If the value of pad_length is negative, less than, or equal to the length of the input string, no padding takes place.
pad_string
The pad_string may be truncated if the required number of padding characters can't be evenly divided by the pad_string's length.
pad_type
Optional argument pad_type can be STR_PAD_RIGHT, STR_PAD_LEFT, or STR_PAD_BOTH. If pad_type is not specified it is assumed to be STR_PAD_RIGHT.
sprintf();
Check php manual sprintf() function in php.net
Along with printf()
can do the job. Check example 7 in the link above.