HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

How can I convert an int to a string and left-pad it with zeros?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
withhowzerosandpadintconvertleftcanstring

Problem

In C# I have an integer value which need to be converted to a string, but it needs to add zeros before:

For Example:

int i = 1;


When I convert it to string it needs to become 0001

Solution

i.ToString().PadLeft(4, '0') - okay, but doesn't work for negative numbers

i.ToString("0000"); - explicit form

i.ToString("D4"); - short form format specifier

$"{i:0000}"; - string interpolation (C# 6.0+)

Context

Stack Overflow Q#4325267, score: 929

Revisions (0)

No revisions yet.