Emitting a colon via format string in .NET

.net, c#, string

Solution

using System;

namespace ConsoleApplication67
{
    class Program
    {
        static void Main()
        {
            WriteRatio(4);
            WriteRatio(0);
            WriteRatio(-200);

            Console.ReadLine();
        }

        private static void WriteRatio(int i)
        {
            Console.WriteLine(string.Format(@"{0:1\:0;-1\:0;\0}", i));
        }
    }
}

gives

1:4
0
-1:200

The `;` separator in format strings means 'do positive numbers like this; negative numbers like this; and zero like this'. The `\` escapes the colon. The third `\` is not strictly necessary as a literal zero is the same as the standard numeric format output for zero :)

Problem

Does anyone know how to construct a format string in .NET so that the resulting string contains a colon? In detail, I have a value, say 200, that I need to format as a ratio, i.e. "1:200". So I'm constructing a format string like this "1:{0:N0}" which works fine. The problem is I want zero to display as "0", not "1:0", so my format string should be something like "{0:1:N0;;N0}", but of course this doesn't work. Any ideas? Thanks!

Original source