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;
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.
Only then a friend of mine showed me how to use
decimal.toString() without an instance of
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.