Jump to content

add leading zeros


jeff5656

Recommended Posts

How do I add leading zeros if the variable does not contain them?

 

I have a list of numbers stored in a VARCHAR field. 

I want the number to always have 3 places, so if a number is 1.25 I want to change it to 001.25

if the number is 12.5 I want to change it to 012.5.  If the number is 123.5 I want to leave it alone.

 

I want to put all the records in a while loop and then check each variable and then update that record if it needs it.

 

What is the best way to do this?  Thanks!

Link to comment
https://forums.phpfreaks.com/topic/265898-add-leading-zeros/
Share on other sites

Ok I fiugured out how to have leading zeros, but then it cuts off the zeros to the right of the decimal point.

 

if I have 1.1 I want it to become 001.100

 

so:

$x = 1.1
$y = sprintf("%03d",$x);
echo $y

answer: 001

 

if I do this:

$x = 1.1
$y = sprintf("%.3f",$x);
echo $y

 

I get 1.100

 

How do I combine this so that I get the leading and the following zeros, i.e. 001.100?

Link to comment
https://forums.phpfreaks.com/topic/265898-add-leading-zeros/#findComment-1362473
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.