首页 > Web开发 > 详细

关于web开发金额每隔三位逗号格式化js

时间:2014-12-19 17:28:08      阅读:428      评论:0      收藏:0      [点我收藏+]

获得焦点并输入效果技术分享,失去焦点效果技术分享


js代码:

<script>
  // 格式化数字成0,000.00
   function formatNumber(value) {
	var result = "";
	var valueParts = value.split(".");
	var mostSignificationDigit = valueParts[0].length -1;   // 最高有效数字位,默认为个位
	var intervalOfDigit = 0; 	// 逗号之间的位数
	var digit, countOfSignificationDigit;
	for (var i = valueParts[0].length -1; i >= 0; i--) {
		digit = valueParts[0][i];
		result = digit + result;
		if (digit != "0") {
			mostSignificationDigit = i;
		}
		if (3 == ++intervalOfDigit) {
			result = "," + result;
			intervalOfDigit = 0;
		}
	}
	if (mostSignificationDigit == -1) {
		result = "0";
	}
	else {
		countOfSignificationDigit = valueParts[0].length - mostSignificationDigit;
		if (countOfSignificationDigit > 3) {
			result = result.substring(result.length - (countOfSignificationDigit%3 == 0 ? countOfSignificationDigit/3 - 1 : countOfSignificationDigit/3)  - countOfSignificationDigit);
		}
		else {
			result = result.substring(result.length - countOfSignificationDigit);
		}
	}
	if (valueParts.length == 2) {
		result += ".";
		var temp = 2 - valueParts[1].length;	// 是否需要补0
		for (var i = 0; i < temp; i++) {
			valueParts[1] += "0"
		}
		result += valueParts[1].substring(0, 2);
	}
	else {
		result += ".00";
	}
	return result;
}
		
// 鼠标再次聚焦文本域,就清除货币格式,显示无格式的数字
function clearAllFormat(obj){
	if(obj!=null&&$(obj).val()!=null&&$(obj).val().trim().length>0){
		var waitToDeleteCommaNumber = $(obj).val();
		var newInputValue = waitToDeleteCommaNumber.replace(/,/g,"");
		$(obj).val(newInputValue.toString());
		return newInputValue.toString();
	}
}
		
		
// 验证是否为浮点数
function checkNumberIsLegal22(obj){
				
	if(!/^[0-9]+(\.[0-9]+){0,1}$/.test(obj)){
		return false;
	}
		return true;
}

// 格式化金额类数字,每三位用逗号分隔,显示的是用逗号分隔的格式化形式
function formatMoneyByComma(obj){
	if(obj!=null&&$(obj).val().trim().length>0&&checkNumberIsLegal22($(obj).val())){
		// 格式化之前,先清除格式
		clearAllFormat(obj);
		if($(obj).val()){
		var currentNumber = $(obj).val();
		$(obj).val(formatNumber(currentNumber));
	}
}
}
</script>


jsp:

<input id="partoutAmount" name="partoutAmount" class="c2" onfocus="clearAllFormat(this)" onblur="formatMoneyByComma(this)"  maxlength="20"  style="text-align:right;height:28px">




关于web开发金额每隔三位逗号格式化js

原文:http://blog.csdn.net/starywx/article/details/42029239

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!