Anand
Anand

Reputation: 1671

How to use a variable format string in string interpolation in C#

I have following code:

var d = 1.25M;
var val = $"{d:#,#.#;(#,#.#);0}";

I would like to vary the formatter e.g. for 2 decimal places: #,#.##;(#,#.##);0 so that it can be passed as a method argument. How would I do that?

Upvotes: 2

Views: 59

Answers (2)

D Stanley
D Stanley

Reputation: 152521

You can't specify the format dynamically with string interpolation - you have to call string.Format

var format = "#,#.##;(#,#.##);0";
var val = string.Format("{0:" + format + "}", d);

You could use string interpolation to define the format, but then you have to "escape" the brackets within the format string:

var format = "#,#.##;(#,#.##);0";
var val = string.Format($"{{0:{format}}}", d);  

Personally I would prefer the string concatenation so I don't have to think about the escaping as much (and there's no functional benefit).

Upvotes: 2

gunr2171
gunr2171

Reputation: 17510

String interpolation ($"") is just syntax sugar for the string.Format method. You can use that directly.

var val2 = string.Format("{0:#,#.#;(#,#.#)}", d);
Console.WriteLine(val2); // "1.3", same as your original code

Upvotes: 2

Related Questions