Converting a negative Integer to String with leading zeros

Quick post for today.

While doing some refactoring I ran into the following code which was intended to convert a negative integer to a string with leading zeros.

int value = GetValue();
string val = "-" + (value * -1).ToString().PadLeft(2, '0');

This can be done much easier. And it works for positive and negative integers. Check the improved code below.

int value = GetValue();
string val = value.ToString("D2");

For a complete list of the possibilities for converting a integer into an string check the MSDN website for Standard Numeric Format Strings:

Happy coding…

  1. +1

  1. No trackbacks yet.