Java/Java 기타
자바에서 소숫점을 특정자리까지 출력하는 2가지 방법
kimc
2022. 2. 10. 22:36
```
자바에서 소수점 특정 자릿수까지 출력하는 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