How to format a decimal without trailing zeros

[亡魂溺海] 提交于 2019-12-01 03:34:50

There are several ways to do it, but since you are converting to a String object anyway, I suppose you could try something like this:

myDecimalVariable.toString("G29");

or, using your code above, assuming 123.00M is your decimal:

123.00M.toString("G29");

Here is the explanation of how that concise example works:

The G format with a number means to format that many significant digits. Because 29 is the most significant digits that a Decimal can have, this will effectively truncate the trailing zeros without rounding.

just apply the Format specifier zero and will remove the trailing zeros:

string test = (1.23M * 100M).ToString("0");
//prints 123.
string test2 = 123.450M.ToString(".00");
//prints 123.45.
string test3 = 123.450M.ToString().Trim('0');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!