프로그래밍/C#
0.3 - 0.1 == 0.2 ?
Scripter
2020. 12. 14. 21:18
C# 언어로 부동소수점수 계산할 때 실수할 수 있는 경우이다.
반복문의 탈출 조건에 저런 것을 이용하다 자칫하면
무한 반복의 늪에 빠질 수 있다.
금액 계산의 경우에 정확한 계산이 요구되기 때문에
float 타입이니 double 타입 보다는 decimal 타입을 사용하는것이
더 바람직할 것이다.
정확한 소수점수 계산을 위해 decimal 타입을 사용한 다음 C# 소스의 실행 결과를 보자.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CalcDecimalConsoleApp
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Use double type:");
Console.WriteLine("{0:F20}", 0.3 - 0.1);
Console.WriteLine("{0}", 0.3 - 0.1 == 0.2);
Console.WriteLine("Use Decimal type:");
Console.WriteLine("{0:F20}", new Decimal(0.3) - new Decimal(0.1));
Console.WriteLine("{0}", new Decimal(0.3) - new Decimal(0.1) == new Decimal(0.2));
}
}
}
/****************************************
Output: -------------------------
Use double type:
0.20000000000000000000
False
Use Decimal type:
0.20000000000000000000
True. . .
****************************************/