Decimal Decision Using Variables Inside String Interpolation

I have a string format that includes two integer variables, each of which must 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"

So far I have managed to get the desired format using the methods of integer variables .ToString():

var xString = x.ToString(xStringFormat);
var yString = y.ToString(yStringFormat);
return $"{xString}-{yString}";

But this seems like overhead, since line interpolation supports the {var: format} format. Is there a way to get my string using only string interpolation without using x and y ToString()?

+4
source share
3 answers

, x y ToSTring()

, ToString("Dx") :

( ):

public string Format(int x, int y, int xDigitCount, int yDigitCount)
{
    return $"{x.ToString($"D{xDigitCount}")}-{y.ToString($"D{yDigitCount}")}";
}

, , VS:

enter image description here

+2

, , string.Format , , - .

:

$"{x:0000000}-{y:000}"

string.Format:

string.Format(
    $"{{0:{new string('0', xFormatDigitCount)}}}-{{1:{new string('0', yFormatDigitCount)}}}",
    x,
    y);

Edit:

weston answer:

$"{x.ToString($"D{xFormatDigitCount}")}-{y.ToString($"D{yFormatDigitCount}")}"
+3

ToString .

$"{x.ToString(xStringFormat)}-{y.ToString(yStringFormat)}"
+1

Source: https://habr.com/ru/post/1623258/


All Articles