Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specify decimal places using variables inside string interpolation

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()?

like image 768
tsemer Avatar asked Jan 07 '16 12:01

tsemer


3 Answers

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}")}"
like image 195
Paulo Morgado Avatar answered Nov 18 '22 09:11

Paulo Morgado


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:

enter image description here

like image 41
weston Avatar answered Nov 18 '22 10:11

weston


You can just call the ToString method within the interpolated string.

$"{x.ToString(xStringFormat)}-{y.ToString(yStringFormat)}"
like image 1
RB. Avatar answered Nov 18 '22 09:11

RB.