How to round a decimal for output?

后端 未结 5 582
醉梦人生
醉梦人生 2020-12-10 10:19

Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do t

相关标签:
5条回答
  • 2020-12-10 10:25

    If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:

    decimal d = ...;
    d = Decimal.Truncate(d * 100) / 100;
    

    And you could create an extension method if you are doing it enough times

    public static class DecimalExtensions
    {
      public static decimal TruncateDecimal(this decimal @this, int places)
      {
        int multipler = (int)Math.Pow(10, places);
        return Decimal.Truncate(@this * multipler) / multipler;
      }
    }
    
    0 讨论(0)
  • 2020-12-10 10:27

    Math.Round Method (Decimal, Int32)

    0 讨论(0)
  • 2020-12-10 10:34

    You can use: Math.Round(number,2); to round a number to two decimal places.

    See this specific overload of Math.Round for examples.

    0 讨论(0)
  • 2020-12-10 10:36

    You don't want to format it then, but to round it. Try the Math.Round function.

    0 讨论(0)
  • 2020-12-10 10:40

    Take a look at Math.Round

    0 讨论(0)
提交回复
热议问题