Specify decimal places using variables inside string interpolation

蓝咒 提交于 2019-12-07 07:05:22

问题


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


回答1:


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:




回答2:


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}")}"



回答3:


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

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


来源:https://stackoverflow.com/questions/34654611/specify-decimal-places-using-variables-inside-string-interpolation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!