◾ 공통
- java.math 패키지에 포함되어 있음
- 문자열이기 때문에 사칙연산이 안됨 (숫자를 계산하기 위해서는 클래스 내부 메서드 이용해야 함)
◾ BigInteger (정수 자료형)
- 문자열 형태로 이루어져 있어 숫자의 범위가 무한함
- 선언방법
BigInteger bigNumber = new BigInteger("1234567890123456789");
- 형변환
BigInteger bigNumber = BigInteger.valueOf(100000); //int -> BigIntger
int int_bigNum = bigNumber.intValue(); //BigIntger -> int
long long_bigNum = bigNumber.longValue(); //BigIntger -> long
float float_bigNum = bigNumber.floatValue(); //BigIntger -> float
double double_bigNum = bigNumber.doubleValue(); //BigIntger -> double
String String_bigNum = bigNumber.toString(); //BigIntger -> String
- 계산
BigDecimal bigNumber1 = new BigDecimal("100000.12345");
BigDecimal bigNumber2 = new BigDecimal("10000");
System.out.println("덧셈(+) :" +bigNumber1.add(bigNumber2));
System.out.println("뺄셈(-) :" +bigNumber1.subtract(bigNumber2));
System.out.println("곱셈(*) :" +bigNumber1.multiply(bigNumber2));
System.out.println("나눗셈(/) :" +bigNumber1.divide(bigNumber2));
System.out.println("나머지(%) :" +bigNumber1.remainder(bigNumber2));
- 비교
BigInteger bigNumber1 = new BigInteger("100000");
BigInteger bigNumber2 = new BigInteger("1000000");
//두 수 비교 compareTo 맞으면 0 틀리면 -1
int compare = bigNumber1.compareTo(bigNumber2);
System.out.println(compare);
◾ BigDecimal (실수 자료형)
- 선언방법
BigDecimal bigNumber = new BigDecimal("123456789.123456789");
[참고]
https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/math/BigInteger.html
BigInteger (Java SE 11 & JDK 11 )
Immutable arbitrary-precision integers. All operations behave as if BigIntegers were represented in two's-complement notation (like Java's primitive integer types). BigInteger provides analogues to all of Java's primitive integer operators, and all relevan
docs.oracle.com
https://coding-factory.tistory.com/604
[Java] 큰 숫자(정수) 다루기 BigInteger 사용법 & 예제 총정리
BigInteger를 사용해야 하는 이유 Type 범위 int -2,147,483,648 ~ 2,147,483,647 long -9,223,372,036,854,775,808 ~ 9,223,372,036,854,775,807 int는 메모리 크기는 4byte로 표현할 수 있는 범위는 -2,147,483,648 ~ 2,147,483,647이고 long
coding-factory.tistory.com
https://coding-factory.tistory.com/605
[Java] 큰 숫자(실수) 다루기 BigDecimal 사용법 & 예제 총정리
BigDecimal을 사용해야 하는 이유 Type 범위 float 1.4E-45 ~ 3.4028235E38 double 4.9E-324 ~ 1.7976931348623157E308 소수점을 저장할 수 있는 타입인 float과 double은 소수점의 정밀도가 완벽하지 않아 값의 오차가 생길
coding-factory.tistory.com
'Back-End > Java' 카테고리의 다른 글
| [ JAVA ] Exception in thread "main" java.lang.ArithmeticException: / by zero (0) | 2023.07.17 |
|---|---|
| [ JAVA ] 자료 형변환 (0) | 2023.07.14 |
| [ JAVA ] String to int, long, short, byte 형 변환 (0) | 2023.07.14 |
| [ JAVA ] Day02 Quiz (0) | 2023.07.14 |
| [ JAVA ] Day01 Quiz (1) | 2023.07.14 |