Vous pouvez utiliser la solution AakashM. Si vous voulez quelque chose un peu plus lisible, vous pouvez créer votre propre fournisseur:
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
}
Avec ce fournisseur, vous pouvez créer des chaînes de format très lisible:
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);
Si vous contrôlez la classe en cours de formatage (plutôt que celui qui est primitif comme Int32), vous pouvez rendre ce look plus agréable. Voir this article pour plus de détails.
Merci pour les réponses à ce jour. Je dois souligner que je sais que je pourrais faire un certain formatage conditionnel comme suggéré, mais j'ai réellement besoin d'une chaîne de format unique - par exemple pour appliquer à une colonne entière de données. – user7239