Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format in .NET: convert integer to fixed width string?

I have an int in .NET/C# that I want to convert to a specifically formatted string.

If the value is 1, I want the string to be "001".

10 = "010".

116 = "116".

etc...

I'm looking around at string formatting, but so far no success. I also won't have values over 999.

like image 713
pearcewg Avatar asked Jun 19 '11 00:06

pearcewg


People also ask

What does %d do in C#?

The %d specifier indicates a placeholder for a decimal number. The width on that suggests it's a 6 digit number.

How do I convert a number to a string in C#?

To convert an integer to string in C#, use the ToString() method.

What is the string .format method used for?

The Java String. format() method returns the formatted string by a given locale, format, and argument. If the locale is not specified in the String. format() method, it uses the default locale by calling the Locale.


1 Answers

The simplest way to do this is use .NET's built-in functionality for this:

var r = 10; var p = r.ToString("000"); 

No need for looping or padding.

like image 118
vcsjones Avatar answered Oct 02 '22 11:10

vcsjones