【问题标题】:Is there a way to format a float with a colon instead of a period?有没有办法用冒号而不是句点格式化浮点数?
【发布时间】:2022-03-01 20:59:50
【问题描述】:

我正在尝试将浮点数(表示 0.0003.000 秒之间的一小段时间)转换为格式为 00:000 的字符串,其中所有前导零都保留。

使用(float).ToString("00.000").Replace(".",":") 有效,但感觉有一种“更好”的方式。

【问题讨论】:

  • 遗憾的是没有,因为我不知道什么“文化”使用这种格式(如果有的话)。我会假设使用nfi.NumberDecimalSeparator = ":" 然后(float).ToString("00.000", nfi) 会起作用,但小数点仍然存在。使用(float).ToString(nfi),也没有考虑到我想要的00:000 格式。 @FranzGleichmann
  • 小数秒通常通过区域性的小数分隔符与整数秒数分隔 - 通常是 ,.

标签: c#


【解决方案1】:

float.ToString() 有一个重载,它采用格式格式提供程序。

组合起来,您可以将前导零和尾随零以及: 作为分隔符:

using System;
using System.Globalization;


public class Test
{
    public static void Main()
    {
        float input = 3.14156F;
        string format = "00.000";
        
        var nfi = new NumberFormatInfo();
        nfi.NumberDecimalSeparator = ":";
        
        string output = input.ToString(format, nfi);
        
        Console.WriteLine(output);
    }
}

output: 03:142

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 1970-01-01
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-03
    • 1970-01-01
    相关资源
    最近更新 更多