How do I display a decimal value to 2 decimal places?

前端 未结 17 2170
没有蜡笔的小新
没有蜡笔的小新 2020-11-21 23:24

When displaying the value of a decimal currently with .ToString(), it\'s accurate to like 15 decimal places, and since I\'m using it to represent dollars and ce

17条回答
  •  悲哀的现实
    2020-11-21 23:58

    Here is a little Linqpad program to show different formats:

    void Main()
    {
        FormatDecimal(2345.94742M);
        FormatDecimal(43M);
        FormatDecimal(0M);
        FormatDecimal(0.007M);
    }
    
    public void FormatDecimal(decimal val)
    {
        Console.WriteLine("ToString: {0}", val);
        Console.WriteLine("c: {0:c}", val);
        Console.WriteLine("0.00: {0:0.00}", val);
        Console.WriteLine("0.##: {0:0.##}", val);
        Console.WriteLine("===================");
    }
    

    Here are the results:

    ToString: 2345.94742
    c: $2,345.95
    0.00: 2345.95
    0.##: 2345.95
    ===================
    ToString: 43
    c: $43.00
    0.00: 43.00
    0.##: 43
    ===================
    ToString: 0
    c: $0.00
    0.00: 0.00
    0.##: 0
    ===================
    ToString: 0.007
    c: $0.01
    0.00: 0.01
    0.##: 0.01
    ===================
    

提交回复
热议问题