将浮点值格式化为特定格式-Java与C#数字格式

我需要将Byte转换为KB.所以我将该值除以1024
我需要显示最初以Java数字格式###,###,###,## 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接口,则它们也可以具有格式.

扫描二维码关注公众号,回复: 8516039 查看本文章
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}”).但是,格式字符串不能是变量,因此这将不起作用:

string format = "{x} KB";
Console.WriteLine($format); // does not compile, use String.Format in this case

备注:

Console.WriteLine还支持格式化,因此上面的示例可以这样编写:

Console.WriteLine("{0:###,###,###,##0.00} KB", 42);

我使用显式String.Format只是为了避免混淆.

更新资料

如果大小格式来自外部来源,则无法将其内联到格式字符串中,但这不是问题.所以如果你有

string fileSizeFormat = "###,###,###,##0.00 KB";

您仍然可以使用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)}";
发布了540 篇原创文章 · 获赞 0 · 访问量 1983

猜你喜欢

转载自blog.csdn.net/weixin_44109689/article/details/103916946
今日推荐