BigDecimal(0.1) + BigDecimal(0.1)의 결과는 0.2일까?

jinwook han·2021년 7월 2일
0

BigDecimal(0.1) + BigDecimal(0.1)의 결과는 0.2일까?
-> 맞다.

코드

@Test
void testBigDecimal() {
    BigDecimal sth1 = new BigDecimal(0.1);
    BigDecimal sth2 = new BigDecimal(0.1);

    assertThat(sth1.add(sth2).doubleValue() == 0.2);
    // true
}

유의점

단, new BigDecimal(0.1).add(new BigDecimal(0.1) 결과를 toString 한 결과는 0.2가 아니다.
0.200000000000000011102...와 같은 형태로 출력한다.

BigDecimal sth1 = new BigDecimal(0.1);
BigDecimal sth2 = new BigDecimal(0.1);

System.out.println(sth1.add(sth2));
// 결과: 0.2000000000000000111022302462515654042363166809082031250

0개의 댓글