Solved

# php function to format number from 1 to 99 to 3 digits

Posted on 2008-10-15
800 Views
Take any number 1 to 100 and format so there are always 3 digits.

Example:

\$numberA = 1;
\$numberB = 10
\$numberC = 85

Now format each as:

\$numberA = 001;
\$numberB = 010;
\$numberC = 085;

So need function that is smart and can take any number 1-99 and format to 3 digits. So if number happens to 100 or 150 then dont touch number!

0

LVL 82

Accepted Solution

hielo earned 300 total points

``````function myFormat(\$str){

\$str=(int)\$str;

if(\$str < 10 )

{

return "00".\$str;

}

elseif(\$str < 100 )

{

return "0".\$str;

}

return \$str;

}
``````
0

LVL 27

Assisted Solution

ddrudik earned 100 total points
A slightly modified version:
``````<?php

function myFormat(\$str){

if(is_int(\$str) && \$str < 100 )

{

\$str=substr('00'.\$str,-3);

}

return \$str;

}

echo myFormat(1).'<br>';

echo myFormat(10).'<br>';

echo myFormat(100).'<br>';

echo myFormat(1000).'<br>';

echo myFormat("FOO").'<br>';

?>
``````
0

LVL 11

Expert Comment

this will do

function format_number(\$number){
return substr("000".\$number, -3);
}

0

LVL 11

Expert Comment

oops sorry repost, please ignore my post
0

LVL 8

Assisted Solution

shanikawm earned 100 total points
use

sprintf("%03d",\$number) or  printf("%03d",\$number)

Attached code prints,

000
005
025
100
150
``````<?php

echo sprintf("%03d",0),"\n";

echo sprintf("%03d",5),"\n";

echo sprintf("%03d",25),"\n";

echo sprintf("%03d",100),"\n";

echo sprintf("%03d",150),"\n";

?>
``````
0

## Featured Post

Introduction Many web sites contain image galleries; a common design for these galleries includes a page with a collection of thumbnail images.  You can click on each of the thumbnail images to see the larger version of the image.  This is easily i…
Consider the following scenario: You are working on a website and make something great - something that lets the server work with information submitted by your users. This could be anything, from a simple guestbook to a e-Money solution. But what…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …