2014/04/21

[Java] 절상, 절하, 반올림

지난번에 javascript에서 절상, 절하, 반올림 처리하는 함수를 올린 적이 있는데
이번엔 그 로직을 살~짝(아주 살짝) 바꿔서 java 함수로 만들었다.
물론 java에서도 Math객체에서 해당 함수들을 지원하지만 몰라서 그런지 정수부분
(원단위, 십단위 등) 또는 소수부분에서의 처리가 안 되는 것 같아서 만들었다.(삽질한 거 아닌지...)
/**
 * 절상, 절하, 반올림 처리
 * @param strMode  - 수식
 * @param nCalcVal - 처리할 값(소수점 이하 데이터 포함)
 * @param nDigit   - 연산 기준 자릿수(오라클의 ROUND함수 자릿수 기준)
 *                   -2:십단위, -1:원단위, 0:소수점 1자리
 *                   1:소수점 2자리, 2:소수점 3자리, 3:소수점 4자리, 4:소수점 5자리 처리
 * @return String nCalcVal
 */
public static String calcMath(String strMode, double nCalcVal, int nDigit) {
    if("CEIL".equals(strMode)) {  //절상
        if(nDigit < 0) {
            nDigit = -(nDigit);
            nCalcVal = Math.ceil(nCalcVal / Math.pow(10, nDigit)) * Math.pow(10, nDigit);
        } else {
            nCalcVal = Math.ceil(nCalcVal * Math.pow(10, nDigit)) / Math.pow(10, nDigit);
        }
    } else if("FLOOR".equals(strMode)) { //절하
        if(nDigit < 0) {
            nDigit = -(nDigit);
            nCalcVal = Math.floor(nCalcVal / Math.pow(10, nDigit)) * Math.pow(10, nDigit);
        } else {
            nCalcVal = Math.floor(nCalcVal * Math.pow(10, nDigit)) / Math.pow(10, nDigit);
        }
    } else {        //반올림
        if(nDigit < 0) {
            nDigit = -(nDigit);
            nCalcVal = Math.round(nCalcVal / Math.pow(10, nDigit)) * Math.pow(10, nDigit);
        } else {
            nCalcVal = Math.round(nCalcVal * Math.pow(10, nDigit)) / Math.pow(10, nDigit);
        }
    }
    return String.valueOf(nCalcVal);
}

댓글 없음:

댓글 쓰기