어제 오늘 내일

[Java Math] floor() 메소드 – 내림 처리하기 본문

IT/Java

[Java Math] floor() 메소드 – 내림 처리하기

hi.anna 2025. 12. 9. 00:20

Math.floor()주어진 수보다 작거나 같은 가장 큰 정수값double 형태로 반환합니다.

즉, 소수점 이하는 무조건 버려지며 아래쪽으로 내림됩니다.

 

1. 기본 사용법

public class MathFloorBasic {
    public static void main(String[] args) {
        System.out.println(Math.floor(3.7));   // 3.0
        System.out.println(Math.floor(7.1));   // 7.0
        System.out.println(Math.floor(-2.3));  // -3.0
        System.out.println(Math.floor(-7.8));  // -8.0
    }
}

양수는 단순히 소수점 이하를 버린 값과 같고, 음수는 더 작은 정수로 내려갑니다.

 

2. 정수로 변환해서 쓰기

public class MathFloorInt {
    public static void main(String[] args) {
        double val = 5.9;
        int roundedDown = (int) Math.floor(val);

        System.out.println(roundedDown); // 5
    }
}

floor()double을 반환하기 때문에 정수형이 필요하면 형 변환을 해줘야 합니다.

 

3. 활용 예제: 할인 가격 계산

public class MathFloorDiscount {
    public static void main(String[] args) {
        double price = 1234.56;

        // 100원 단위로 내림
        int discounted = (int) (Math.floor(price / 100) * 100);

        System.out.println("할인 적용 금액 = " + discounted); // 1200
    }
}

가격을 특정 단위로 내릴 때 활용할 수 있습니다.

 

4. 활용 예제: 페이지 시작 번호 계산

public class MathFloorPagination {
    public static void main(String[] args) {
        int currentPage = 7;
        int itemsPerPage = 10;

        int startIndex = (int) Math.floor((double)(currentPage - 1) / 1) * itemsPerPage;
        System.out.println("페이지 시작 인덱스 = " + startIndex); // 60
    }
}

목록 페이징 처리에서 시작 인덱스를 계산할 때도 유용합니다.

 

결론

  • Math.floor()는 항상 아래쪽 정수로 내림
  • 반환 타입은 double
  • 음수일 때는 더 작은 정수로 내려감에 주의
  • 가격 내림, 페이지 인덱스 계산 등에서 활용 가능

 

 

반응형
Comments