c# pass in data formatting string at runtime
i would like to be able to pass in a format string at runtime and have it applied against a nominal data value.
for example, the incoming format string could look anything like the standard c# format types:
{0:c}, {0:d}, #,###,###
i want to be able to accept the string value and apply the format at runtime. some pseudocode
private string FormatAtRunTime(formatstring)
{
string formattedOutput = "";
decima开发者_如何学Cl datavalue = 2.4600;
datavalue.ToString(formatstring); ??????
return formattedOutput;
}
I think you just want:
string formattedOutput = string.Format(formatstring, datavalue);
The fact that the first argument isn't a string literal (as most calls to Format
probably are) is irrelevant.
Note that calling datavalue.ToString(formatstring)
would be fine if formatstring
were a single format specifier, e.g. "c" or even "0.000" - but it can't be a composite format string as your example gives. For that, you need string.Format
.
精彩评论