Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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.

like image 376
Alan2 Avatar asked Dec 08 '25 11:12

Alan2


2 Answers

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"
like image 82
Alen Genzić Avatar answered Dec 10 '25 00:12

Alen Genzić


public string PhraseNum { get => $"Id: {_phraseNum:D5}"; set => SetProperty(ref _phraseNum, value); }
like image 41
Sanan Fataliyev Avatar answered Dec 09 '25 23:12

Sanan Fataliyev