코딩테스트/정리노트

[Java] Math.round 관련

_Hiiro 2022. 9. 26. 07:37

Java 에서 숫자에 대한 반올림 기능을 수행할 수 있는 메소드로 Math.round()를 제공한다.

※ 참고로 올림과 내림은 Math.ceil() / Math.floor() 이다.

import java.lang.Math;

float varfloat1 = 5.2f;
float varfloat2 = 5.8f;

System.out.println(Math.round(varfloat1));  // 5
System.out.println(Math.round(varfloat2));  // 6
  • 기본적으로 round 메소드는 인자로 주어지는 수의 소수점 첫째 자리에서 반올림한 수를 반환한다.
float varfloat = 5.2f;
double vardouble = 5.8f;

int varint = Math.round(varfloat);

// int varlong = Math.round(vardouble); // 컴파일 오류 발생!
long varlong = Math.round(vardouble);
  • 주의해야 할 부분은 인자 값으로 float 값이 주어지느냐 double로 주어지느냐에 따라 반환 값의 타입이 각각 int, long으로 달라진다는 점이다. 그 이유는 int, float가 4바이트 크기의 자료형이고 long과 double이 8바이트의 자료형이기 때문이다.

같이 알아두기 : String.format()

Math.round() 메소드와 마찬가지로 반올림 기능을 수행하는 메소드로 String.format()을 함께 알아두자.

float varfloat1 = 5.2f;
double varfloat2 = 5.8f;

int varint = Math.round(varfloat1);

String varstr1 = String.format("%.0f", varfloat1);   // 5
String varstr2 = String.format("%.0f", varfloat2);   // 6
  • 물론 String 클래스의 메소드이므로 반환값이 String임을 잊으면 안된다.