double 타입 변수 0.1 에 0.2를 더한 결과는 0.3으로 출력될까?

jinwook han·2021년 7월 3일
0

double 타입 변수 0.1 에 0.2를 더한 결과는 0.3으로 출력될까?
-> 아니오.
-> 0.30000000000000004으로 출력한다.

코드

@Test
void testDouble() {
    double sth1 = 0.1;
    double sth2 = 0.1;

    System.out.println(sth1+sth2);
    // 결과값: 0.30000000000000004
}

유의점

실제 0.3과 비교 시 같다고 나오므로 유의한다.
double 타입 간의 비교다.
오차범위 내에서 차이가 없으면 같다고 판단하는 것 같다.

@Test
void testDouble() {
    double sth1 = 0.1;
    double sth2 = 0.2;

    System.out.println(sth1+sth2); 
    // 결과값: 0.30000000000000004
    
    assertThat(sth1+sth2 == 0.3);
    // 결과값: true
}

0개의 댓글