How to round a decimal for output?

后端 未结 5 591
醉梦人生
醉梦人生 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;
      }
    }
    

提交回复
热议问题