Today I spend A LOT OF time on trying to display a percentage – string representation of a decimal but without trailing zeros, e.g. 15.1% instead of 15.10%.
In the application I already had NumberFormatInfo for displaying monetary values and percentages. An object of that type was defined as follows:
NumberFormatInfo nfi = new NumberFormatInfo(); nfi.PercentDecimalDigits = 2; // some additional settings for nfi // (including monetary and numeric attributes)
Let’s take the following decimals as examples:
decimal d = 0.241534545765; decimal d2 = 0.241; decimal d3 = 0.2;
Having nfi I could get a string representation of a decimal as below:
d.toString("P", nfi); //24.15%
d2.toString("P", nfi); //24.10%
d3.toString("P", nfi); //20.00%
As you see nfi was defined so that only two decimal places were displayed, but always, disregarding the fact whether they are zeros or not. I tried to find a member of NumberFormatInfo class, a hint of how to use it for that purpose (including parsing the string as a result of toString with passing nfi – sick!), but unfortunately I failed.
Solution
Only then a friend of mine showed me how to use decimal.toString() without an instance of NumberFormatInfo class.
d.toString("0.##%"); //24.15%
d2.toString("0.##%"); //24.1%
d3.toString("0.##%"); //20%
It’s worth mentioning that weren’t there ‘%’ character in the expression passed to toString method I would first have to multiply the decimals by 100:
(d * 100).toString("0.##"); //24.15%
(d2 * 100).toString("0.##"); //24.1%
(d3 * 100).toString("0.##"); //20%
That’s it… It’s frustrating I couldn’t fix it myself in a couple of minutes. However at the end of the day the problem is solved, which is a good news.
![C#, decimal.toString(), and how to get rid of trailing zeros Photo Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_e.png?x-id=e7f743fe-669d-4003-a289-18b5624ff996)


Hey!
Thanks for this, finding good documentation from microsoft about formatting is a pain. Also this does not work for all datatypes, just decimal (and probably float etc), anyway, thanks again.
Thanks for this. Now I use this to have a ‘human’ display (do not display the trailing zeros):
decimal d = 12.103000m;
Console.WriteLine(d.ToString(“#.################################”, CultureInfo.InvariantCulture));
///Ouput: 12.103
Anyne have a better solution?
Maybe it’s not better, but works:
public static string ToTrimmedString(this decimal value)
{
return value.ToString().TrimEnd(‘0′, CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator[0]);
}
I believe my suggestion is safer. Thanks for the tip anyway!
You should use
value.ToString(“G29″);
this makes exactly what you want. It uses the most compact representation of the Decimal value by removing all trailing zeros, no matter how many non-zero values are in front of them.
Check the explanation of the G (General) specifier for numeric formating at the docs.