首页 > 解决方案 > 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.

标签: c#

解决方案


最简单的方法是ToString使用以下格式调用 int 对象上的方法:

using System.Globalization;

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

推荐阅读