본문 바로가기

ASP.net with C# (웹폼)

C# 반올림, 올림, 버림 - 0.5는 왜 1이 안되는가?

반올림은 매우 간단하게 Round() 함수를 이용하면 됩니다. 하지만 반올림이 여러분이 생각하는 것처럼 동작하지 않는다면 이번글을 끝까지 읽어주시기 바랍니다. 이번글 에서는 Math클래스의 Round(), Ceiling(), Truncate() 메소드 등을 이용한 반올림, 올림, 버림 방법에 대해 알아보겠습니다. 특히 반올림에서는 우리가 일반적으로 생각하는 .5가 1이 되도록 하기위해선 MidpointRounding.AwayFromZero를 사용해야 함을 특히 주의하시기 바랍니다.

 

반올림 - Math.Round()

        double val1 = 2.1;
        double val2 = 2.5;
        double val3 = 2.6;
        double val4 = 2.71;

        int result1 = (int)Math.Round(val1); //result1 : 2
        int result2 = (int)Math.Round(val2); //result2 : 2
        int result3 = (int)Math.Round(val3); //result3 : 3

        int result4 = (int)Math.Round(val2, MidpointRounding.ToEven); //result4 : 2
        int result5 = (int)Math.Round(val2, MidpointRounding.AwayFromZero); //result5 : 3

        double result6 = Math.Round(val4, 1); //result6 : 2.7 소숫점 첫째자리로 반올림 

반올림에서 주의할 것은 Math.Round(2.5)의 결과가 3이 아니라는 겁니다. 이러한 결과를 원한다면 AwayFormZero를 사용해야 합니다. 아래의 표를 참고하세요.

원래수 AwayFromZero ToEven 비고
3.5 4 4  
2.8 3 3  
2.5 3 2  
2.1 2 2  
-2.1  -2  -2   
-2.5  -3  -2   
-2.8  -3  -3   
-3.5  -4  -4   

올림 - Math.Ceiling()

        double val1 = 2.1;
        double val2 = 2.5;
        double val3 = 2.6;

        int result1 = (int)Math.Ceiling(val1); //result1 : 3
        int result2 = (int)Math.Ceiling(val2); //result2 : 3
        int result3 = (int)Math.Ceiling(val3); //result3 : 3

버림 - Math.Truncate()

        double val1 = 2.1;
        double val2 = 2.5;
        double val3 = 2.6;

        int result1 = (int)Math.Truncate(val1); //result1 : 2
        int result2 = (int)Math.Truncate(val2); //result2 : 2
        int result3 = (int)Math.Truncate(val3); //result3 : 2

 

자료참고 : MSDocs(바로가기)