I have a string format which includes two integer variables, each of which needs to be formatted to a variable length:
int x = 1234;
int y = 42;
// Simplified, real values come from method outputs, so must use the variables:
int xFormatDigitCount = 7;
int yFormatDigitCount = 3;
var xStringFormat = new string('0', xFormatDigitCount); // "0000000"
var yStringFormat = new string('0' ,yFormatDigitCount); // "000"
For now I only managed to get the desired format using the integer variables' .ToString()
methods:
var xString = x.ToString(xStringFormat);
var yString = y.ToString(yStringFormat);
return $"{xString}-{yString}";
But this seems like an overhead since string interpolation supports the format {var:format}. Is there a way to get my string with only string interpolation, without using x and y's ToString()
?
I'm not sure I understand the question, but format specifiers for string.Format
and, thus, string interpolation are textual - they don't accept variables.
You either use static format specifiers:
$"{x:0000000}-{y:000}"
Or resort to the good old string.Format
:
string.Format(
$"{{0:{new string('0', xFormatDigitCount)}}}-{{1:{new string('0', yFormatDigitCount)}}}",
x,
y);
Edit:
Based on weston's answer:
$"{x.ToString($"D{xFormatDigitCount}")}-{y.ToString($"D{yFormatDigitCount}")}"
Is there a way to get my string with only string interpolation, without using x and y's ToSTring()
I don't believe so, but it can be so much cleaner thanks to ToString("Dx")
:
All in one (nested interpolations):
public string Format(int x, int y, int xDigitCount, int yDigitCount)
{
return $"{x.ToString($"D{xDigitCount}")}-{y.ToString($"D{yDigitCount}")}";
}
Stack Overflow syntax highlighting can't keep up, so it looks odd, but this is how it looks in VS:
You can just call the ToString
method within the interpolated string.
$"{x.ToString(xStringFormat)}-{y.ToString(yStringFormat)}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With