정리/Java
자바의 정석 28강 반올림 Math.round(), 나머지 연산자
민발자
2023. 4. 27. 21:12
728x90
ch 3-11,12 반올림 Math.round(), 나머지 연산자
1. 반올림 Math.round()
실수를 소수점 첫 째자리에서 반올림한 정수를 반환
public static void main(String args[]) {
double pi = 3.141592;
System.out.println(pi);
double shortPi = Math.round(pi * 1000) / 1000.0;
System.out.println(shortPi);
System.out.println(Math.round(pi*1000)); // 3142
System.out.println(Math.round(pi*1000)/1000); // 3 int로 나누면 int반환
System.out.println(Math.round(pi*1000)/1000.0); // 3.142
// 소수점 3째자리에서 절삭하려면?
System.out.println(pi*1000); // 3141.592
System.out.println((int)(pi*1000)); // 3141
System.out.println((int)(pi*1000)/1000.0); // 3.141
}
2. 나머지 연산자 %
나누고 남은 나머지 반환 피연산자는 0이 아닌 정수만 허용 부호 무시
728x90