Specify decimal places using variables inside string interpolation

血红的双手。 提交于 2019-12-05 08:54:45

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:

Paulo Morgado

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

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

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