Best way to display decimal without trailing zeroes

前端 未结 14 1477
终归单人心
终归单人心 2020-11-27 04:49

Is there a display formatter that will output decimals as these string representations in c# without doing any rounding?

// decimal -> string

20 -> 20         


        
14条回答
  •  广开言路
    2020-11-27 04:55

    I have end up with this variant:

    public static string Decimal2StringCompact(decimal value, int maxDigits)
        {
            if (maxDigits < 0) maxDigits = 0;
            else if (maxDigits > 28) maxDigits = 28;
            return Math.Round(value, maxDigits, MidpointRounding.ToEven).ToString("0.############################", CultureInfo.InvariantCulture);
        }
    

    Advantages:

    you can specify the max number of significant digits after the point to display at runtime;

    you can explicitly specify a round method;

    you can explicitly control a culture.

提交回复
热议问题