简体   繁体   中英

c# - Convert number in string to have certain number of digits

I have a number in string format. This number will be between 1-6 digits and i need to convert it to be filled with zeroes on left side in order to always be 6 digit number. Is there any more efficient way than this?

Int32.Parse("5").ToString("D6")

Conversion to int just feels a bit unnecessary.

You could use String.PadLeft :

string result = number.PadLeft(6, '0');

If the number can be negative this doesn't work and you need your int.Parse approach.

这是不必要的

string result = "5".PadLeft(6,'0');

string someText = "test 5 rate";

someText = Regex.Replace(someText, @"\\d+", n => n.Value.PadLeft(5, '0'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM