Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I do this in PHP..Number formatting

Tags:

php

numbers

Hey im sure this is pretty simple..but im not exactly sure how to ask the question so searching the forums were difficult.

I have a variable with a number in it ... lets say $number.....the variable has a single regular number...1 or 2 or 34 or 102 etc

I need to change it to something like this

001, 002, 034, 102

So the first 2 place values are 00 for single digit numbers or 0 of double digits.

Any ideas?

Thanks for your help

Craig

like image 710
spork141 Avatar asked Dec 07 '25 12:12

spork141


2 Answers

You can use sprintf.

$num = 2;
$num = sprintf("%03u", $num);

echo $num; // prints 002
like image 118
smottt Avatar answered Dec 10 '25 00:12

smottt


str_pad()

echo str_pad($number,3,'0',STR_PAD_LEFT);
like image 27
Mark Baker Avatar answered Dec 10 '25 02:12

Mark Baker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!