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

前端 未结 17 2421
没有蜡笔的小新
没有蜡笔的小新 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:54

    Mike M.'s answer was perfect for me on .NET, but .NET Core doesn't have a decimal.Round method at the time of writing.

    In .NET Core, I had to use:

    decimal roundedValue = Math.Round(rawNumber, 2, MidpointRounding.AwayFromZero);
    

    A hacky method, including conversion to string, is:

    public string FormatTo2Dp(decimal myNumber)
    {
        // Use schoolboy rounding, not bankers.
        myNumber = Math.Round(myNumber, 2, MidpointRounding.AwayFromZero);
    
        return string.Format("{0:0.00}", myNumber);
    }
    

提交回复
热议问题