0

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 = "";
   decimal datavalue = 2.4600;

   datavalue.ToString(formatstring);   ??????

   return formattedOutput;
}
2
  • And what's the problem, exactly? Have you tried something? Commented Oct 10, 2011 at 6:39
  • what issue are you experiencing? Commented Oct 10, 2011 at 6:39

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

good guess, but in any case a good explanation about data.ToString() and ´String.Format()` :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.