How to round decimal value up to nearest 0.05 value?

后端 未结 6 2164
醉梦人生
醉梦人生 2020-12-03 07:33

Is there any way to round up decimal value to its nearest 0.05 value in .Net?

Ex:

7.125 -> 7.15

6.66 -> 6.7

If its now available can anyone

相关标签:
6条回答
  • 2020-12-03 07:48

    Use this:

    Math.Round(mydecimal / 0.05m, 0) * 0.05m;
    

    The same logic can be used in T-SQL:

    ROUND(@mydecimal / 0.05, 0) * 0.05
    

    I prefer this approach to the selected answer simply because you can directly see the precision used.

    0 讨论(0)
  • 2020-12-03 07:50

    I could not get proper rounding in most of the formulas

    This one "rounds" to nearest

    float roundFloat(float value, float toNearest) {
                float divVal = (1 / (toNearest == 0 ? 1 : toNearest));
                return ((float)(Math.Round(value * divVal)) / divVal);
            }
    

    Result:

    roundFloat(2, 0.125F); -> 2
    roundFloat(2.11, 0.125F); -> 2.125
    roundFloat(2.22, 0.125F); -> 2.25
    roundFloat(2.33, 0.125F); -> 2.375
    roundFloat(2.44, 0.125F); -> 2.5
    roundFloat(2.549999, 0.125F); -> 2.5
    roundFloat(2.659999, 0.125F); -> 2.625
    roundFloat(2.769999, 0.125F); -> 2.75
    roundFloat(2.879999, 0.125F); -> 2.875
    roundFloat(2.989999, 0.125F); -> 3
    

    Example 0.125 nearest rounding

     2.000 
     2.125 
     2.250 
     2.375 
     2.500 
     2.625 
     2.750 
     2.875 
     3.000 
    
    0 讨论(0)
  • 2020-12-03 07:54

    Duplicated here and here for ruby and python. It shouldn't be too different.

    0 讨论(0)
  • 2020-12-03 07:59

    How about:

    Math.Ceiling(myValue * 20) / 20
    
    0 讨论(0)
  • 2020-12-03 08:01

    Something like this should work for any step, not just 0.05:

    private decimal RoundUp (decimal value, decimal step)
    {
        var multiplicand = Math.Ceiling (value / step);
        return step * multiplicand;
    }
    
    0 讨论(0)
  • 2020-12-03 08:03

    Math..::.Round Method (Decimal, Int32, MidpointRounding)

    Rounds a double-precision floating-point value to the specified number of fractional digits. A parameter specifies how to round the value if it is midway between two other numbers.

       Math.Round(1.489,2,MidpointRounding.AwayFromZero)
    
    0 讨论(0)
提交回复
热议问题