Home > Blockchain >  How to use a variable format string in string interpolation in C#
How to use a variable format string in string interpolation in C#

Time:10-22

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?

CodePudding user response:

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

CodePudding user response:

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).

  •  Tags:  
  • c#
  • Related