我需要将Byte转换为KB。因此,我将该值除以1024
。
我需要按照Java Number formatting中最初指定的格式显示该值 ###,###,###,##0.00 KB
这段代码
string format="###,###,###,##0.00 KB";
return String.Format(format, x);
产生以下输出###,###,###,##0.00 KB
这个格式化字符串是在Java中指定的,同样的方法在C#中是否可行?请给出建议。
我需要将Byte转换为KB。因此,我将该值除以1024
。
我需要按照Java Number formatting中最初指定的格式显示该值 ###,###,###,##0.00 KB
这段代码
string format="###,###,###,##0.00 KB";
return String.Format(format, x);
产生以下输出###,###,###,##0.00 KB
这个格式化字符串是在Java中指定的,同样的方法在C#中是否可行?请给出建议。
String.Format
和IFormattable.ToString
(在这里需要格式化)是不同但相关的东西。
String.Format
需要一些带有占位符的格式字符串,替换的值如果实现了IFormattable
接口也可以进行格式化。Console.WriteLine(String.Format("{0} KB", 42.ToString("###,###,###,##0.00")));
42的格式可以内联:
Console.WriteLine(String.Format("{0:###,###,###,##0.00} KB", 42));
通过插值可以进一步简化:
最初的回答
Console.WriteLine($"{42:###,###,###,##0.00} KB"));
42
可以在插值表达式中作为一个变量($"{numValue:###,###,###,##0.00} KB}"
)。但是,格式化字符串不能是一个变量,所以以下代码将不起作用: Original Answer翻译成"最初的回答"
string format = "{x} KB";
Console.WriteLine($format); // does not compile, use String.Format in this case
备注:
Console.WriteLine
还支持格式化输出,因此上面的示例也可以像这样编写:
Console.WriteLine
也支持格式化输出,所以上述示例也可以按以下方式编写:
Console.WriteLine("{0:###,###,###,##0.00} KB", 42);
我使用显式的 String.Format
只是为了避免混淆。
如果大小格式来自外部源,您无法将其嵌入到格式字符串中,但这并不是问题。因此,如果您有
string fileSizeFormat = "###,###,###,##0.00 KB";
myFloatWithFileSize.ToString(fileSizeFormat)
。在这种情况下,只需要使用String.Format
,如果你想嵌入到一个漂亮的句子中: 你仍然可以使用myFloatWithFileSize.ToString(fileSizeFormat)
。在这种情况下,只需要使用String.Format
,如果你想将其嵌入到漂亮的句子中:
return String.Format("The size of the file: {0}", fileSize.ToString(fileSizeFormat));
return $"The size of the file: {fileSize.ToString(fileSizeFormat)}";
###,###,###,##0.00 KB
将由服务器提供并存储在字符串中。在这种情况下,我该如何正确设置格式?此外,格式可能会受到服务器更改的影响。基本上,这应该支持普通的Java数字格式化。 - techno