Server-side/java
실수 소수점 이하 표현 방법
그곰
2023. 9. 14. 09:42
1. String.format()을 이용한 표현 방법
public static void main(String[] args) {
double val1 = 3;
double val2 = 3.14;
System.out.println(String.format("%.1f", val1));
System.out.println(String.format("%.1f", val2));
// 출력 결과
// val1 = 3 --> 3.0
// val2 = 3.14 --> 3.1
}
위 출력 결과와 같이 실수 값이 소수점 이하가 자릿수를 맞추기 위해 0으로 채워지는 현상이 발생된다.
2. java.text.DecimalFormat의 format을 이용한 표현 방법
public static void main(String[] args) {
double val1 = 3;
double val2 = 3.14;
System.out.println((new DecimalFormat("#.#")).format(val1));
System.out.println((new DecimalFormat("#.#")).format(val2));
// 출력 결과
// val1 = 3 --> 3
// val2 = 3.14 --> 3.1
}
위 출력 결과와 같이 String.format()을 이용하였을때 발생된 소수점 이하 자릿수만큼 0으로 채워지는 현상이 없다.
하여 실수에 대한 소수점 이하를 표현해야하는 경우 각 상황에 맞추어 사용하면 된다.