Francis Ducharme
Francis Ducharme

Reputation: 4987

Variable decimal formating in string interpolation

I have looked around for this, but I'm not sure it's possible with string interpolation (I'm using VS2015).

string sequenceNumber = $"{fieldValuePrefix.ToUpper()}{separator}{similarPrefixes + 1:D4}";

Is there any way to make D4 a variable ? Some say yes, some no. Apparently, VS2015 C#6.0 is able to do it.

This works, it will return a string like WMT-0021, depending on fieldValuePrefix (WMT), separator (-) and the value of similarPrefixes (20). But I'd like the "D4" part to be a method argument instead of hardcoded in there.

Any ideas ?

Upvotes: 1

Views: 542

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205629

You can, but you have to use explicit ToString call like this:

string format = "D4";
string sequenceNumber = 
    $"{fieldValuePrefix.ToUpper()}{separator}{(similarPrefixes + 1).ToString(format)}";

Upvotes: 5

Related Questions