Вы можете использовать решение AakashM. Если вы хотите что-то более читабельное, вы можете создать своего собственного провайдера:
internal class RatioFormatProvider : IFormatProvider, ICustomFormatter
{
public static readonly RatioFormatProvider Instance = new RatioFormatProvider();
private RatioFormatProvider()
{
}
#region IFormatProvider Members
public object GetFormat(Type formatType)
{
if(formatType == typeof(ICustomFormatter))
{
return this;
}
return null;
}
#endregion
#region ICustomFormatter Members
public string Format(string format, object arg, IFormatProvider formatProvider)
{
string result = arg.ToString();
switch(format.ToUpperInvariant())
{
case "RATIO":
return (result == "0") ? result : "1:" + result;
default:
return result;
}
}
#endregion
}
С этим провайдером вы можете создавать очень удобочитаемые строки формата:
int ratio1 = 0;
int ratio2 = 200;
string result = String.Format(RatioFormatProvider.Instance, "The first value is: {0:ratio} and the second is {1:ratio}", ratio1, ratio2);
Если вы управляете форматируемым классом (а не примитивным, таким как Int32), вы можете сделать это более привлекательным. Подробнее см. в этой статье .