Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Decimal.Round() 메서드 완벽 정리 – 반올림 구문부터 예제까지

C#에서 Decimal.Round() 메서드는 decimal 형식의 값을 가장 가까운 정수 또는 지정한 소수 자릿수로 반올림할 때 사용합니다. 금액 계산처럼 높은 정밀도가 요구되는 작업에서 특히 유용하며, 반올림 방식까지 세부적으로 제어할 수 있습니다.

구문(Syntax)

Decimal.Round() 메서드는 다음과 같이 네 가지 오버로드를 제공합니다.

public static decimal Round (decimal d);
public static decimal Round (decimal d, int decimals);
public static decimal Round (decimal d, MidpointRounding mode);
public static decimal Round (decimal d, int decimals, MidpointRounding mode);
  • d : 반올림할 decimal 값입니다.
  • decimals : 결과에 유지할 소수 자릿수입니다(0~28 범위).
  • mode : 중간값(절반 지점에 있는 값)을 어떻게 처리할지 결정하는 MidpointRounding 열거형입니다.

기본 반올림 규칙과 MidpointRounding

.NET의 기본 반올림 방식은 은행가 반올림(Banker's Rounding)입니다. 즉, 중간값이 등장하면 가장 가까운 짝수 쪽으로 반올림합니다(MidpointRounding.ToEven). 예를 들어 0.5는 0으로, 1.5는 2로 반올림됩니다. 흔히 아는 "소수점 아래가 5면 무조건 올린다"는 사사오입 방식을 원한다면 MidpointRounding.AwayFromZero를 직접 지정해야 합니다.

또한 decimals 인수가 0~28 범위를 벗어나면 ArgumentOutOfRangeException이 발생하고, 연산 결과가 decimal 표현 범위를 초과하면 OverflowException이 발생할 수 있으니 주의해야 합니다.

예제 1 : 가장 가까운 정수로 반올림

소수 자릿수를 지정하지 않으면 값이 가장 가까운 정수로 반올림됩니다.

using System;

public class Demo {
    public static void Main() {
        Decimal val1 = 9.00m;
        Decimal val2 = 15.29m;
        Decimal val3 = 394949845.14245M;

        Console.WriteLine("Decimal 1 = " + val1);
        Console.WriteLine("Decimal 2 = " + val2);
        Console.WriteLine("Decimal 3 = " + val3);

        Console.WriteLine("Value 1 (Rounded) = " + Decimal.Round(val1));
        Console.WriteLine("Value 2 (Rounded) = " + Decimal.Round(val2));
        Console.WriteLine("Value 3 (Rounded) = " + Decimal.Round(val3));
    }
}

실행 결과

Decimal 1 = 9.00
Decimal 2 = 15.29
Decimal 3 = 394949845.14245
Value 1 (Rounded) = 9
Value 2 (Rounded) = 15
Value 3 (Rounded) = 394949845

예제 2 : 소수 자릿수 지정하여 반올림

두 번째 인수로 원하는 소수 자릿수를 전달하면 해당 자릿수까지만 남기고 반올림됩니다.

using System;

public class Demo {
    public static void Main() {
        Decimal val1 = 6.59m;
        Decimal val2 = 30.12m;
        Decimal val3 = 6946649845.25245M;

        Console.WriteLine("Decimal 1 = " + val1);
        Console.WriteLine("Decimal 2 = " + val2);
        Console.WriteLine("Decimal 3 = " + val3);

        Console.WriteLine("Value 1 (Rounded) = " + Decimal.Round(val1, 1));
        Console.WriteLine("Value 2 (Rounded) = " + Decimal.Round(val2, 1));
        Console.WriteLine("Value 3 (Rounded) = " + Decimal.Round(val3, 2));
    }
}

실행 결과

Decimal 1 = 6.59
Decimal 2 = 30.12
Decimal 3 = 6946649845.25245
Value 1 (Rounded) = 6.6
Value 2 (Rounded) = 30.1
Value 3 (Rounded) = 6946649845.25

정리

Decimal.Round()는 인자 조합에 따라 정수 단위 반올림, 소수 자릿수 지정 반올림, MidpointRounding을 활용한 세밀한 반올림 제어까지 모두 가능합니다. 특히 금융·회계 로직을 작성할 때는 기본값인 은행가 반올림(ToEven)과 사사오입 방식(AwayFromZero)의 차이를 반드시 숙지해야 의도치 않은 계산 오차를 막을 수 있습니다.