我们正在将我们的代码从 C++ 升级到 C#,并且在很多地方我们正在格式化字符串。 例如,我们有类似的东西:
OurString.Format("amount = %0.2Lf", (long double)amount);
如何将 %0.2Lf 转换成 C# 格式? 我试过下面的代码,但它不一样
string formatString = String.Format("amount = {0}", (long double)amount));
谢谢
最佳答案
使用格式字符串:http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
您可能需要 N2
或 F2
,具体取决于是否包含千位分隔符。所以,
string formatString = String.Format("amount = {0:F2}", amount);
编辑:
作为一个简单的 FYI,如果您在一系列不同的步骤中构造一个字符串,您可能需要使用 StringBuilder
类,它有一个 AppendFormat()
接受与 string.Format()
相同格式选项的方法:
var builder = new StringBuilder();
// ... Your code to build the first part of the string
builder.AppendFormat("amount = {0:F2}", amount);
// ... whatever else you need to add
builder.ToString(); // outputs your final/completed string.
是否使用 StringBuilder
取决于内存管理和/或性能对应用程序的重要性; C# 中的字符串是不可变的,因此当您连接它们时,您实际上是在创建一个全新的字符串。您可以在此处阅读更多信息:http://msdn.microsoft.com/en-us/library/system.string.aspx#Immutability
关于c# - String.Format - 从 C++ 迁移到 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18247234/