Correct Format for Strings/Numbers Beginning with Zero

How can I format a number into a string with leading zeros?

Rather simple:

Key = i.ToString("D2");

D stands for "decimal number", 2 for the number of digits to print.

Correct format for strings / numbers beginning with zero?

Either:

// Set the value explicitly as a string
$objPHPExcel->getActiveSheet()->setCellValueExplicit('A1', '0029', PHPExcel_Cell_DataType::TYPE_STRING);

or

// Set the value as a number formatted with leading zeroes
$objPHPExcel->getActiveSheet()->setCellValue('A3', 29);
$objPHPExcel->getActiveSheet()->getStyle('A3')->getNumberFormat()->setFormatCode('0000');

String.Format for Phonenumber leading with zeros

You would use 000 instead of ###, read more about format in MSDN article Custom Numeric Format Strings

String.Format("{0:(000) ###-####}", double.Parse(@e.Phone));

Format specifier "0"

Replaces the zero with the corresponding digit if one is present;
otherwise, zero appears in the result string.

Format specifier "#"

Replaces the "#" symbol with the corresponding digit if one is
present; otherwise, no digit appears in the result string.

Best way to format integer as string with leading zeros?

You can use the zfill() method to pad a string with zeros:

In [3]: str(1).zfill(2)
Out[3]: '01'

Number formatting: how to convert 1 to 01, 2 to 02, etc.?

Here is the MSDN article on formatting numbers. To pad to 2 digits, you can use:

n.ToString("D2")

Display number with leading zeros

In Python 2 (and Python 3) you can do:

number = 1
print("%02d" % (number,))

Basically % is like printf or sprintf (see docs).


For Python 3.+, the same behavior can also be achieved with format:

number = 1
print("{:02d}".format(number))

For Python 3.6+ the same behavior can be achieved with f-strings:

number = 1
print(f"{number:02d}")

How to format a Java string with leading zero?

In case you have to do it without the help of a library:

("00000000" + "Apple").substring("Apple".length())

(Works, as long as your String isn't longer than 8 chars.)

How to convert a number to a string but formatted with x number of digits

You can use the ToString formatting Dn to output leading zeroes:

var d = 5;
var s2 = d.ToString("D2");
var s10 = d.ToString("D10");
Console.WriteLine(s2);
Console.WriteLine(s10);

The output is:

05
0000000005


Related Topics



Leave a reply



Submit