标签:
在网页中有时需要将用户输入的金额数字转换为人民币大写显示出来,下面的提供的方法可以完美地自动完成这个功能(最多转换13位整数)
<!DOCTYPE html> <html> <head> <title>numberToChineseCapital</title> <meta charset="utf-8"> </head> <body> <input type="text" id="number" style="width: 200px;"> <span id="chinese"></span> </body> <script type="text/javascript" src="http://cdn.bootcss.com/jquery/1.11.3/jquery.min.js"></script> <script> function numberToChineseCapital(number) { if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(number)) { return ‘数字格式不正确!‘; } number += ‘00‘; var unit = ‘万千百十亿千百十万千百十元角分‘, pointIndex = number.indexOf(‘.‘), chineseCapitalStr = ‘‘; // 如果有小数,截取整数位和小数位 if (pointIndex !== -1) { number = number.substring(0, pointIndex) + number.substr(pointIndex + 1, 2); } // 根据输入金额的长度匹配对应的单位 unit = unit.substr(unit.length - number.length); for (var i = 0; i < number.length; i++) { chineseCapitalStr += ‘零壹贰叁肆伍陆柒捌玖‘.charAt(number.charAt(i)) + unit.charAt(i); } return chineseCapitalStr .replace(/零(千|百|十|角)/g, ‘零‘) .replace(/(零)+/g, ‘零‘) .replace(/零(万|亿|元)/g, ‘$1‘) .replace(/(亿)万|元(拾)/g, ‘$1$2‘).replace(/^元零?|零分/g, ‘‘) .replace(/千/g, ‘仟‘) .replace(/百/g, ‘佰‘) .replace(/十/g, ‘拾‘) .replace(/元$/g, ‘元整‘); } $(‘#number‘).keyup(function() { $(‘#chinese‘).text(numberToChineseCapital($(this).val())); }); </script> </html>
标签:
原文地址:http://www.cnblogs.com/happyfreelife/p/5379276.html