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

后端 未结 9 2021
慢半拍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: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();
    

提交回复
热议问题