Home > Back-end >  Is there a way to format a float with a colon instead of a period?
Is there a way to format a float with a colon instead of a period?

Time:03-01

I'm trying to convert a float (which represents a small time period between 0.000 and 3.000 seconds) into a string in the format 00:000, where all leading zeros remain.

Using (float).ToString("00.000").Replace(".",":") works, but it feels like there's a "better" way.

CodePudding user response:

float.ToString() has an overload that takes both a format and a formatprovider.

In combination, you can have both your leading and trailing zeroes and : as separator:

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

  •  Tags:  
  • c#
  • Related