插值字符串格式问题

编程入门 行业动态 更新时间:2024-10-23 02:40:18
本文介绍了插值字符串格式问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我几次偶然发现了一个内插字符串的问题.

I have stumbled upon one issue with interpolated strings for a several times now.

请考虑以下情况:

double number = 123.4567; var str = $"{{{number:F2}}}"; //I want to get "{123.45}" Console.WriteLine(str); // Will print "{F2}"

起初有点令人惊讶,但是一旦您意识到花括号是如何配对的,就很有意义了.以下两个大括号是插值字符串中单个大写的转义序列.因此,插值表达式的左括号与字符串中的最后一个花括号配对.

A little surprising at first but once you realize how the curly brackets are paired it makes sense. Two following curly brackets are an escape sequence for a single curly in the interpolated string. So the opening bracket of the interpolated expression is paired with the last curly in the string.

___pair____ | | $"{{{number:F2}}}";

现在,您可以执行以下操作来中断转义序列:

Now you could do the following to break the escape sequence:

var str = $"{{{number:F2} }}"; // This will be "{123.45 }"

请注意此方法将空格字符添加到输出中.(不理想)

Notice the space character this approach adds to the output. (Not ideal)

我的问题:

让我们说我想使用单个内插字符串来获取确切的输出"{123.45}"

Lets say I want to use a single interpolated string to get exactly the output "{123.45}"

如果不进行以下操作,这完全有可能吗?

Is this at all possible without doing something hackish like the following?

var s = $"{{{number:F2}{'}'}";

推荐答案

假设不需要使用命名格式字符串,则可以使用:

Assuming that it is not required to use a named format string, you can use:

var s = $"{{{number:#.#0}}}";

更多推荐

插值字符串格式问题

本文发布于:2023-11-08 14:06:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569585.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   插值   格式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!