How do you round a number to two decimal places in C#?

后端 未结 15 1001
挽巷
挽巷 2020-11-22 08:59

I want to do this using the Math.Round function

15条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 09:37

    If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#

    Let's see what happens if you want to round to the 3rd decimal:

    double result = 0.75d * 0.95d; // result = 0.71249999999999991
    double result = 0.75f * 0.95f; // result = 0.71249997615814209
    
    result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
    result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
    

    As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.

    This applies to negative numbers:

    double result = -0.75 * 0.95;  //result = -0.71249999999999991
    result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
    result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
    

    So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:

    double Redondea(double value, int precision, bool roundUp = true)
    {
        if ((decimal)value == 0.0m)
            return 0.0;
    
        double corrector = 1 / Math.Pow(10, precision + 2);
    
        if ((decimal)value < 0.0m)
        {
            if (roundUp)
                return Math.Round(value, precision, MidpointRounding.ToEven);
            else
                return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
        }
        else
        {
            if (roundUp)
                return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
            else
                return Math.Round(value, precision, MidpointRounding.ToEven);
        }
    }
    

    The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.

提交回复
热议问题