-2

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.

Luc
  • 174
  • 10
  • Does this answer your question? [How to change symbol for decimal point in double.ToString()?](https://stackoverflow.com/questions/3135569/how-to-change-symbol-for-decimal-point-in-double-tostring) – Franz Gleichmann Mar 01 '22 at 12:36
  • Sadly not, as I don't know what "culture" uses this format (if any). I would assume that using `nfi.NumberDecimalSeparator = ":"` then `(float).ToString("00.000", nfi)` would work, but the decimal point remains. Using `(float).ToString(nfi)`, doesn't take into account the `00:000` formatting I want either. @FranzGleichmann – Luc Mar 01 '22 at 12:45
  • 2
    Fractional seconds are normally separated from the whole number of seconds by the culture's decimal separator - usually either `,` or `.` – phuzi Mar 01 '22 at 12:55

1 Answers1

3

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

Franz Gleichmann
  • 3,420
  • 4
  • 20
  • 30