2

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?

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

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.