user5405648
user5405648

Reputation:

C#: Pad number with 0 from the left until length is X characters?

I am trying to pass a number with 0's, until its 3 or more characters. I've done a not-so-dynamic approach below, but I was wondering if C# had anything built in?

For example, "77" would become "077", "6" would become "006", and "63" would become "063"

Is there a built in / better way?

            _totalSupplierCount = GetTotalSupplierNumberForInvoices().ToString().Left<double>(3);

            _totalSupplierCountStr = _totalSupplierCount.ToString();

            if (_totalSupplierCountStr.Length == 2)
            {
                _totalSupplierCountStr = "0" + _totalSupplierCountStr;
            }

            if (_totalSupplierCountStr.Length == 1)
            {
                _totalSupplierCountStr = "000" + _totalSupplierCountStr;
            }

Upvotes: 1

Views: 583

Answers (2)

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48327

Yes, there is a better method. You could repeat 0 character by 3 - your_string_length times.

For avoiding any error / exception you could use an if condition.

if(_totalSupplierCountStr.Length < 3) {
    _totalSupplierCountStr = new String('0', 3 - _totalSupplierCountStr.Length) + _totalSupplierCountStr;
}

Another approach could be using PadLeft method.

_totalSupplierCountStr = _totalSupplierCountStr.PadLeft(3, '0');

Upvotes: 0

canton7
canton7

Reputation: 42225

Take a look at the page on Standard numeric format strings, particularly the "D" specifier.

The precision specifier indicates the minimum number of digits desired in the resulting string. If required, the number is padded with zeros to its left to produce the number of digits given by the precision specifier.

This means you can alter your ToString() call to use the format "D3", which will pad up to 3 digits with 0's as necessary:

int totalSupplierCount = 3;
string totalSupplierCountStr = totalSupplierCount.ToString("D3");

You might prefer to use the slightly shorter:

string totalSupplierCountStr = $"{totalSupplierCount:D3}";

Upvotes: 3

Related Questions