소수점 n번째 자리에서 반올림

이지현·2024년 3월 1일

다음과 같이 pi값이 있을 때, 소수점 4번째 자리에서 반올림 하는 여러 방법이 있다.

float pi = 3.141592f;
  1. printf() 사용
System.out.printf("%.3f", pi);	// 3.142
  1. String.format() 사용 (변수에 저장할 수 있음)
float result = Float.parseFloat(String.format("%.3f", pi));
System.out.println(result);
  1. 절삭 후 0.5 더한 뒤, int로 변형 (변수에 저장할 수 있음)
// pi*1000 == 3141.592
// pi*1000+0.5 == 3142.0920
// (int)(pi*1000+0.5) == 3142
// (int)(pi*1000+0.5)/1000f == 3.142

float result = (int)(pi*1000+0.5)/1000f;
System.out.println(result); 	// 3.142
profile
병아리 개발자

0개의 댓글