c# - Format a string like you would a numeric value -
i have string format same way numeric value. ex:
int num = 2; string option = num.tostring("000"); console.writeline(option); //output //002
but way can think format parse int, apply tostring("000") method it.
string option = "2"; option = int.parse(option).tostring("000");
is there better, more direct way this?
no, there no built-in mechanism "format" string if number. options:
- use string functions (
pad
,length
,substring
) determine characters should added - parse numeric type , use
tostring
numeric formatting strings - use reqular expression extract digits , generate new string
there's not 1 "right" answer. each has risks , benefits in terms of safety (what if string not represent valid integer?), readability, performance, etc.
Comments
Post a Comment