【问题标题】:Formatting Float Value to specific Format - Java vs C# Number Formatting将浮点值格式化为特定格式 - Java 与 C# 数字格式
【发布时间】:2019-10-02 06:10:05
【问题描述】:

我需要将字节转换为 KB。所以我将值除以 1024 我需要以这种格式显示原来在 Java Number 格式中指定的值###,###,###,##0.00 KB

这段代码

 string format="###,###,###,##0.00 KB";
 return String.Format(format, x);

产生以下输出 ###,###,###,##0.00 KB

此格式化字符串在 Java 对应项中指定,相同的方法在 C# 中不起作用吗? 请指教。

【问题讨论】:

    标签: java c# formatting number-formatting


    【解决方案1】:

    String.FormatIFormattable.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}")。但是,格式字符串不能是变量,所以这不起作用:

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

    【讨论】:

    • 非常感谢 :) .. 此值 ###,###,###,##0.00 KB 将由服务器提供,并将存储在字符串中。在这种情况下如何正确设置格式?格式也会被服务器更改。基本上这应该支持正常的 Java 数字格式
    猜你喜欢
    • 1970-01-01
    • 2011-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-27
    • 2016-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多