2014/04/21

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

고민하다 나름 간략하게 만들어 본다고 한건데
아래의 방식으로 처리가 안되는 경우가 있으려나?

//param : strMode - 수식
//param : nCalcVal - 처리할 값(소수점 이하 데이터 포함)
//param : nDigit    - 연산 기준 자릿수
//       => -2:십단위, -1:원단위
//           , 0:소수점 1자리, 1:소수점 2자리, 2:소수점 3자리, 3:소수점 4자리, 4:소수점 5자리 처리
function xxx(strMode, nCalcVal, nDigit) {
    if(strMode == "CEIL") {  //절상
        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(strMode == "FLOOR") { //절하
        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 = (nCalcVal / Math.pow(10, nDigit)).toFixed(0) * Math.pow(10, nDigit); 
        } else {
            nCalcVal = nCalcVal.toFixed(nDigit)
        }
    }
    return nCalcVal;
}

댓글 없음:

댓글 쓰기