```
자바에서 소수점 특정 자릿수까지 출력하는 2가지 방법
```

이번 글을 통해 배워갈 내용
- 자바에서 주어진 소수점까지 출력하기
소수 0.12345678를 소수점 3자리까지만 출력하고자 하는 경우
아래와 같은 방법들이 있습니다.
// 방법 1
System.out.println(Double.valueOf(new DecimalFormat("#.###").format(0.12345678)));
// 방법 2
System.out.println((double)Math.round(0.12345678 * 1000) / 1000);
편의에 따라서 위에 #의 개수를 조절하거나 곱하는 수 1000을 다르게 해서 소수점을 조정 가능합니다.
전체 코드는 아래와 같습니다
import java.io.IOException;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws IOException {
double exampleNumber = 0.123456789;
System.out.println();
// 방법 1
System.out.println(Double.valueOf(new DecimalFormat("#.###").format(exampleNumber)));
// 방법 2
System.out.println((double) Math.round(exampleNumber * 1000) / 1000);
}
}
읽어주셔서 감사합니다
무엇인가 얻어가셨기를 바라며
오늘도 즐거운 코딩 하시길 바랍니다 ~ :)
참조
https://stackoverflow.com/questions/13210491/math-round-java
Math round java
I got project do convert from cm to inch. I did it: how can i round my number with Math.round? import java.util.Scanner; public class Centimer_Inch { public static void main (String[] args) { ...
stackoverflow.com
728x90
'Java > Java 기타' 카테고리의 다른 글
| JAVA로 시스템 환경 값 가지고 오기 (0) | 2022.03.25 |
|---|---|
| JAVA로 시스템 속성에 값넣고 값가지고 오기 (0) | 2022.03.25 |
| 자바에 리스트 내부 중복된 원소 지우는 두가지 방법 (0) | 2022.02.24 |
| 자바 모든 스트링 한문자로 바꾸는 3가지 방법 (0) | 2022.02.10 |
| Azure에서 사용할 JDK 에 대한 생각 (0) | 2021.11.20 |