1

Using PHP I want to format a number(7) like in 6 digits 000007

I had done this via printf Function but wanted to store it in a variable how can I do so.

Below mentioned code not working, giving output as :000007 and printing it on screen:

$gensubjectid=printf("%06d\n", $origionalsubjectid);

Suggest.

3
  • sprintf() should do what you need Commented Apr 17, 2014 at 8:22
  • printf returns the length of the outputted string Commented Apr 17, 2014 at 8:22
  • Dude printf of sprintf not working Below is appropriate solution. $input = 7; str_pad($input, 6, "0", STR_PAD_LEFT); Commented Apr 18, 2014 at 9:04

3 Answers 3

7

Use sprintf - it's identical to printf but it returns the formatted string.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use: spirntf

$unformattedNumber = 7;  
$formattedNumber = sprintf('%06d', $unformattedNumber);

Or you can try this (str_pad):

$input = 7;
str_pad($input, 6, "0", STR_PAD_LEFT);

Comments

0

Use str_pad().

$invID = str_pad($invID, 10, '0', STR_PAD_LEFT);

Or

Use sprintf: http://php.net/function.sprintf

$number = 51;
$number = sprintf('%10d',$number);
print $number;
// outputs 0000000051

$number = 8051; $number = sprintf('%10d',$number); print $number; // outputs 0000008051

1 Comment

This is what I want I am getting accurate result as I want it is really very help full.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.