Jump to content


Photo

# of digits


  • Please log in to reply
7 replies to this topic

#1 briant

briant
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 18 August 2006 - 04:54 PM

Should be simple but I can't seem to find what the function is called.

I want a number like 1 to have 5 digits, like 00001. Or a number like 528 to be 00528.
Theres a long way to do it like if id is 1 digit add 0000 but then that takes too long and I'm sure there is a function out there.

Thank you

#2 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 18 August 2006 - 04:56 PM

I believe you are looking for printf()

For example:
for($num = 1; $num <= 10; $num++)
{
    printf("%05d", $num);

    echo "<br />\n";
}


#3 briant

briant
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 18 August 2006 - 05:01 PM

For some reason I can't seem to find it there. I don't think that's it.

#4 wildteen88

wildteen88
  • Staff Alumni
  • Advanced Member
  • 10,482 posts
  • LocationUK, Bournemouth

Posted 18 August 2006 - 05:18 PM

Printf is the same as sprintf so prehaps have a read of how to use sprintf function.

printf will do what you want to to do from what I can tell from your thread.
// an unformated number:
$num = '523';

// now we format it, so it is a 5 digit number with 
// zeros at beginning to pad the number to be five digits
$num = printf("%05d", $num);

// print our new formated number:
echo $num;
// the result should be 00523


#5 Ifa

Ifa
  • Members
  • PipPipPip
  • Advanced Member
  • 88 posts
  • LocationRauma, Finland

Posted 18 August 2006 - 05:26 PM

If you don't wan't to echo it,
$num = str_pad($num, 5, "0", STR_PAD_LEFT);
I'm just a guy who likes to code for fun...

#6 ryanlwh

ryanlwh
  • Staff Alumni
  • Advanced Member
  • 511 posts

Posted 18 August 2006 - 05:51 PM

wildteen, should be
$num = sprintf("%05d", $num);

Please use EDIT * 100...
Please use
or [php] * 1000...

PLEASE READ THE POSTED SOLUTIONS CAREFULLY * 1000000...

#7 briant

briant
  • Members
  • PipPipPip
  • Advanced Member
  • 50 posts

Posted 18 August 2006 - 06:27 PM

Thanks everyone, I think Ifa's thingy-ma-jig was what I was looking for but thanks wildteen88 for your help, I believe I'm able to use that too. Thanks again everyone.

#8 Barand

Barand
  • Moderators
  • Sen . ( ile || sei )
  • 18,021 posts

Posted 18 August 2006 - 07:54 PM

If it the id from a MySql table, you can define it as
id INT(5) NOT NULL AUTO_INCREMENT ZEROFILL

Then will be zero-filled automatically.
If you are still using mysql_ functions, STOP! Use mysqli_ or PDO. The longer you leave it the more you will have to rewrite.

Donations gratefully received






moon.png

|baaGrid| easy data tables - and more
|baaChart| easy line, column and pie charts




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users