C# Math.Round Up

前端 未结 2 641
甜味超标
甜味超标 2021-01-29 09:37

I\'ve got a question.

I have a decimal and I want to round this at 2 decimals, not at the ordinary way but

0.2013559322033898305084745763

desired result:

相关标签:
2条回答
  • 2021-01-29 10:16

    It sounds like you want a version of Math.Ceiling, but which takes a number of decimal places. You could just multiply, use Math.Ceiling, then divide again:

    public static double CeilingWithPlaces(double input, int places)
    {
        double scale = Math.Pow(10, places);
        double multiplied = input * scale;
        double ceiling = Math.Ceiling(multiplied);
        return ceiling / scale;
    }
    

    (If you only ever need 2 decimal places of course, you can hard-code the scale of 100, as Dennis_E's answer does.)

    Now, two caveats about this:

    • There may very well be situations where the fact that we're performing multiple operations works against you. Floating point maths can be weird like that, particularly with floating binary point. (Heck, the idea of "decimal places" with floating binary point is already problematic.)
    • That will always round up, i.e. away from negative infinity. So it would round -0.201 to -0.20. If you want to round away from 0, you may need to handle negative values separately, e.g. with

      if (input < 0)
      {
          return -CeilingWithPlaces(-input, places);
      }
      
    0 讨论(0)
  • 2021-01-29 10:23

    Not directly, so you have to use a trick:

    Math.Ceiling(x * 100) / 100;
    
    0 讨论(0)
提交回复
热议问题