jeff5656 Posted July 18, 2012 Share Posted July 18, 2012 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! Quote Link to comment https://forums.phpfreaks.com/topic/265898-add-leading-zeros/ Share on other sites More sharing options...
BuildMyWeb Posted July 18, 2012 Share Posted July 18, 2012 sprintf() or alternatively str_pad() http://www.php.net/manual/en/function.sprintf.php Quote Link to comment https://forums.phpfreaks.com/topic/265898-add-leading-zeros/#findComment-1362431 Share on other sites More sharing options...
jeff5656 Posted July 18, 2012 Author Share Posted July 18, 2012 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? Quote Link to comment https://forums.phpfreaks.com/topic/265898-add-leading-zeros/#findComment-1362473 Share on other sites More sharing options...
xyph Posted July 18, 2012 Share Posted July 18, 2012 The first number must specify the TOTAL length, including decimal, of the string. <?php $x = 1.1; $y = sprintf("%07.3f",$x); echo $y; // 001.100 ?> Quote Link to comment https://forums.phpfreaks.com/topic/265898-add-leading-zeros/#findComment-1362483 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.