JavaScript 货币格式化

在金融系统或财务系统中,需要将输入的数值转换为货币,方便用户查看  可以通过javascript进行实现

要求:

       1、不能使用中文输入   style="ime-mode: disabled"

       2、有焦点左对齐,无焦点右对齐并显示千分位

            text-align: right

       3、不允许粘贴非法值  调用onpaste()

       4、非数值

           不限制: 8 退格

                        46 删除

                        37-40 方向键

                        48-57 小键盘数字

                        96-105 大键盘数字

                        110,190 大小键盘小数点

                        189,,109 负号

                        13 回车

 

代码如下:

<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>templates</title>
		<script type="text/javascript">
			//判断输入是否合法的ascii
			function moneyKeyDown() {
				var k = window.event.keyCode;
				return isValidNum(k);
			}

			function isValidNum(k) {
				return ((k == 8) || (k == 46) || (k >= 37 && k <= 40) || (k >= 48 && k <= 57) || (k >= 96 && k <= 105) || (k == 110) || (k == 190) || (k == 189) || (k == 109) || (k == 13));
			}

			//不允许粘贴非法值
			function moneyPaste() {
				var d = clipboardData.getData("Text");
				for(var i = 0; i < d.length; i++) {
					var c = d.charCodeAt(i);
					if(!isValidNum(c)) {
						return false;
					}
				};
			}

			function outputMoney(number) {
				number = number.replace(/\,/g, "");
				if(number == "")
					return "";
				if(number < 0)
					return '-' + outputDollars(Math.floor(Math.abs(number) - 0) + '') + outputCents(Math.abs(number) - 0);
				else
					return outputDollars(Math.floor(number - 0) + '') + outputCents(number - 0);
			}

			function outputDollars(number) {
				if(number.length <= 3)
					return (number == '' ? '0' : number);
				else {
					var mod = number.length % 3;
					var output = (mod == 0 ? '' : (number.substring(0, mod)));
					for( i = 0; i < Math.floor(number.length / 3); i++) {
						if((mod == 0) && (i == 0))
							output += number.substring(mod + 3 * i, mod + 3 * i + 3);
						else
							output += ',' + number.substring(mod + 3 * i, mod + 3 * i + 3);
					}
					return (output);
				}
			}

			function outputCents(amount) {
				amount = Math.round(((amount) - Math.floor(amount) ) * 100);
				return (amount < 10 ? '.0' + amount : '.' + amount);
			}
		</script>
	</head>
	<body>
		<center>
			<input type="text" name="money1" onkeydown="return moneyKeyDown()"
			onpaste="return moneyPaste()"
			onfocus="this.style.textAlign='left';this.value=this.value.replace(/,/g,'')"
			onblur="this.style.textAlign='right';this.value=outputMoney(this.value)"
			style="ime-mode: disabled;text-align: right" />
		</center>
	</body>
</html>

 

你可能感兴趣的:(javascrip,货币格式)