Alan2
Alan2

Reputation: 24572

How can I format a variable and make it into a string with a message and zeros in front of it?

My code has this for PhraseNum:

public string PhraseNum { get => _phraseNum; set => SetProperty(ref _phraseNum, value); }

What I would like is for instead of just displaying the number, that it displays something like this:

Id: 00044

So with the characters "Id:" in front, then a space and then padded to five digits.

Upvotes: 3

Views: 81

Answers (2)

Sanan Fataliyev
Sanan Fataliyev

Reputation: 630

public string PhraseNum { get => $"Id: {_phraseNum:D5}"; set => SetProperty(ref _phraseNum, value); }

Upvotes: 3

Alen Genzić
Alen Genzić

Reputation: 1418

Simplest way is to call the ToString method on the int object with a format:

using System.Globalization;

int _phraseNum = 123;
_phraseNum.ToString("Id: 00000", CultureInfo.InvariantCulture); //outputs "Id: 00123"

Upvotes: 6

Related Questions