How to format a decimal without trailing zeros

前端 未结 3 1123
走了就别回头了
走了就别回头了 2021-01-11 13:29

I\'ve just learned that a decimal somehow remembers how much trailaing zero\'s were needed to store a number. With other words: it remembers the size of the fraction.

<
3条回答
  •  独厮守ぢ
    2021-01-11 13:51

    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.

提交回复
热议问题