[Java] Math.round()로 반올림하기

2024. 8. 1. 15:36Java/연산자

Math.round()는 소수점 첫째 자리에서 반올림한다. 실수를(float과 double) 매개변수로 넣을 수 있다. 만일 소수점 첫째 자리가 아닌 다른 자리에서 반올림하려면 1-의 n제곱으로 곱한 다음에 나누면 된다. 이 때 실수로 나누어야 값이 제대로 표기된다. 

 

public class test {
  public static void main(String[] args) {
    double pi = 3.14159265358979323846;
    double shortPi = Math.round(pi*1000)/1000.0;
    System.out.println(shortPi);
  }
}

연산 결과

 

더보기

 

public static int round(float a)
Returns the closest int to the argument, with ties rounding to positive infinity.

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Integer.MIN_VALUE, the result is equal to the value of Integer.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Integer.MAX_VALUE, the result is equal to the value of Integer.MAX_VALUE.

Parameters:a - a floating-point value to be rounded to an integer.Returns:the value of the argument rounded to the nearest int value.

 

public static long round(double a)
Returns the closest long to the argument, with ties rounding to positive infinity.

Special cases:

  • If the argument is NaN, the result is 0.
  • If the argument is negative infinity or any value less than or equal to the value of Long.MIN_VALUE, the result is equal to the value of Long.MIN_VALUE.
  • If the argument is positive infinity or any value greater than or equal to the value of Long.MAX_VALUE, the result is equal to the value of Long.MAX_VALUE.

Parameters:a - a floating-point value to be rounded to a long.Returns:the value of the argument rounded to the nearest long value.

 

 

'Java > 연산자' 카테고리의 다른 글

[Java] 연산자 연습문제 풀이  (0) 2024.08.01
[Java] 연산자란 무엇인가?  (0) 2024.08.01