How to round up value C# to the nearest integer?

后端 未结 9 1985
慢半拍i
慢半拍i 2020-11-28 09:02

I want to round up double to int.

Eg,

double a=0.4, b=0.5;

I want to change them both to integer.

so that

         


        
相关标签:
9条回答
  • 2020-11-28 09:26

    Math.Round

    Rounds a double-precision floating-point value to the nearest integral value.

    0 讨论(0)
  • 2020-11-28 09:28

    Check out Math.Round. You can then cast the result to an int.

    0 讨论(0)
  • 2020-11-28 09:28

    Use a function in place of MidpointRounding.AwayFromZero:

    myRound(1.11125,4)
    

    Answer:- 1.1114

    public static Double myRound(Double Value, int places = 1000)
    {
        Double myvalue = (Double)Value;
        if (places == 1000)
        {
            if (myvalue - (int)myvalue == 0.5)
            {
                myvalue = myvalue + 0.1;
                return (Double)Math.Round(myvalue);
            }
            return (Double)Math.Round(myvalue);
            places = myvalue.ToString().Substring(myvalue.ToString().IndexOf(".") + 1).Length - 1;
        } if ((myvalue * Math.Pow(10, places)) - (int)(myvalue * Math.Pow(10, places)) > 0.49)
        {
            myvalue = (myvalue * Math.Pow(10, places + 1)) + 1;
            myvalue = (myvalue / Math.Pow(10, places + 1));
        }
        return (Double)Math.Round(myvalue, places);
    }
    
    0 讨论(0)
  • 2020-11-28 09:30

    Another option:

    string strVal = "32.11"; // will return 33
    // string strVal = "32.00" // returns 32
    // string strVal = "32.98" // returns 33
    
    string[] valStr = strVal.Split('.');
    
    int32 leftSide = Convert.ToInt32(valStr[0]);
    int32 rightSide = Convert.ToInt32(valStr[1]);
    
    if (rightSide > 0)
        leftSide = leftSide + 1;
    
    
    return (leftSide);
    
    0 讨论(0)
  • 2020-11-28 09:31

    Math.Round(0.5) returns zero due to floating point rounding errors, so you'll need to add a rounding error amount to the original value to ensure it doesn't round down, eg.

    Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
    Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
    Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
    Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
    Console.ReadKey();
    
    0 讨论(0)
  • It is simple. So follow this code.

    decimal d = 10.5;
    int roundNumber = (int)Math.Floor(d + 0.5);
    

    Result is 11

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