js 포맷 화폐 포맷

2626 단어 포맷
//  
function initCurrencyField(){
	$("input.currency").each(function(){
		$(this).val(formatCurrency($(this).val()));
		//  
		$(this).focus(function(){
			$(this).val(trim($(this).val()));
		});
		
		$(this).blur(function(){
			var value = $(this).val();
			if(!isDouble(value)){
				alert(" ");
				$(this).val(0);
				$(this).focus();
				return;
			}
			$(this).val(formatCurrency(value));
		});
	});
}

function isDouble(value) {
	var Double = /^[-\+]?\d+(\.\d+)?$/;
	value = value.replace(/,/g, '');
	return Double.test(value);
};

function formatCurrency(value) {
    if (MRound(value, 6) == 0) {
        return "0.00";
    }

    var v = '' + value;
    v = v.replace(/[¥,]/g, '');
    var prefix  = '';
    if (v.indexOf("-") == 0) {
    	prefix = v.substring(0, 1);
    	v = v.substring(1);
    }
    
    var s = '';
    if (v.indexOf(".") != -1) {
        var index = v.indexOf(".");
        s = v.substring(index);
        var moreOne = 0;
        if (s.length > 3) {
            var num = parseInt(s.substring(1, 3), 10);
            if (parseInt(s.substring(3, 4), 10) > 4) {
                num++; //  
                if (num >= 100) {
                	moreOne++;
                	num = num - 100;
                }
            }
            if (num < 10) {
				s = ".0" + num;
			} else {
				 s = "." + num;
			}
            if (s.length == 2) {
            	s += '0';
            }
        } else if (s.length == 2) {
            s += '0';
        }
        v = v.substring(0, index);
        if (moreOne > 0) {
        	v = parseFloat(v) + moreOne;
        }
    } else {
        s = '.00';
    }
    var len = v.length;

    while (len > 3) {
        s = ',' + v.substring(len - 3) + s;
        v = v.substring(0, len - 3);
        len -= 3;
    }
    s = prefix + v + s;

    return s;
}

function MRound(m, n) {
    return Math.round(m * Math.pow(10, n)) / Math.pow(10, n);
}

function trim(str) {
	return str.trim().replace(/[¥,%]/g, '');
}

좋은 웹페이지 즐겨찾기