1

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;
            }
canton7
  • 37,633
  • 3
  • 64
  • 77

2 Answers2

3

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}";
canton7
  • 37,633
  • 3
  • 64
  • 77
0

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');
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
  • 2
    If you're taking the string manipulation approach why not use [`PadLeft`](https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft?view=net-5.0) (as given in the comments on the question), rather than rolling your own version? – canton7 May 07 '21 at 08:53
  • @canton7, I specified in my answer the approach you're mentioning. Thanks for your point! – Mihai Alexandru-Ionut May 07 '21 at 08:57