英文:
Can you format an int to have characters before it?
问题
我使用一个键值来识别销售应用中的报价,该应用是使用C#编写的,使用MVC Core 6。我想要在键值前面添加两个字母代码,并且知道如何在键值上填充零(这一部分我知道如何做)。是否可以使用格式设置来实现这个目标?我正在使用EntityFramework,所以希望它可以自动显示为以下样式。
例如,1会显示为QU000001,而200会显示为QU000200。
谢谢。
英文:
I'm using a key value to identify quotes in a sales app written in c# using MVC Core 6. I'd like to pad the key value with zeros (which I know how to do) but also have it display with a two letter code ahead of it. Can this be done with formatting? I'm using EntityFramework, so I want it to display like that automatically.
For example, 1 would look like QU000001, and 200 would look like QU000200.
Thanks.
答案1
得分: 3
你可以使用左填充来在数字前添加前导零,以确保你始终得到一个6位数的字符串:
var myString = "QU" + myNumber.ToString().PadLeft(6, '0');
英文:
You can using a left-padding to add leading zeros to your number, so that you allways get a 6-digit string:
var myString = "QU" + myNumber.ToString().PadLeft(6, '0');
答案2
得分: 0
你可以使用 Substring
string Base = "QU000000";
int Value = 200;
int LengthBase = Base.Length;
int LengthValue = Value.ToString().Length;
string _result = Base.Substring(0, LengthBase - LengthValue) + Value.ToString();
//结果:QU000200
英文:
You can use Substring
string Base = "QU000000";
int Value = 200;
int LengthBase = Base.Length;
int LengthValue = Value.ToString().Length;
string _result = Base.Substring(0, LengthBase - LengthValue) + Value.ToString();
//Result:QU000200
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论