目前网上有许多的数字转人民币大写功能,但是在某些数字上就回出现错误,
比如501356,这个转换之后,有的会转换成 “伍拾万零壹仟叁佰伍拾陆” ,单位万和千紧密相连,中间是不需要 “零” 的。 (属于个人见解).
具体代码如下,贴出整个页面
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script type='text/javascript'>
intChars= prompt("请输入数字:","20");
_char=toChars(intChars);
alert(_char);
//传入数字,转成人民币大写 如1234.5=》 壹仟贰佰叁拾肆元伍角
function toChars(chars){
var _MaxNumber = 99999999999.99;
// 判断输入格式
chars = chars.toString();
if (chars == "") {
alert("不能为空 请输入数字金额!如:123.23");
return "";
}
if ((chars).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
alert("请输入正确的数字!");
return "";
}
//标准化输入数字格式
chars = chars.replace(/,/g, ""); //删除逗号分隔符。
chars = chars.replace(/^0+/, ""); //替换掉数字开头的0;
//判断数字长度不超过最大长度
if (Number(chars) > _MaxNumber) {
alert("超出限定数字长度");
return "";
}
return GetChar(chars);
}
function GetChar(chars) {
var CN_SYMBOL = "";
var integral; //整数
var decimal; //小数
var outChars; //输出字符
//从货币数字的转换
//整数和小数部分分离处理
var parts = chars.split(".");
if (parts.length > 1) {
integral = parts[0];
decimal = parts[1];
//获取小数位后两位
decimal = decimal.substr(0, 2);
}
else {
integral = parts[0];
decimal = "";
}
outChars=GetInteger(integral);
// 确认并输出最终返回字符串
outChars =outChars == ""? '零元':outChars + GetDecimals(decimal);
outChars = CN_SYMBOL+ outChars;
return outChars;
}
//得到整数部分
function GetInteger(integral)
{
var i, p, d;
var quotient, modulus;
var _digits, _radices, _bigRadices
//准备相应的数字特征数组
_digits = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
_radices =['','拾','佰','仟'];
_bigRadices =['','万','亿'];
//---开始-----
outChars = "";
//判断大于0的处理
if (Number(integral) > 0) {
var _count = 0;
for (i = 0; i < integral.length; i++) {
p = integral.length - i - 1;
d = integral.substr(i, 1);
quotient = p / 4;
modulus = p % 4;
if (d == "0") {
_count++;
}
else {
if (_count > 0)
{
outChars += _digits[0];
}
_count = 0;
outChars += _digits[Number(d)] + _radices[modulus];
}
if (modulus == 0 && _count < 4) {
outChars += _bigRadices[quotient];
_count=0;
}
}
outChars += '元';
}
return outChars;
}
//得到小数部分
function GetDecimals(decimal){
var _decimals =['角','分'];
var _digits = ['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];
var outChars="";
//处理小数部分
if (decimal != "") {
for (i = 0; i < decimal.length; i++) {
d = decimal.substr(i, 1);
if (d != "0") {
outChars += _digits[Number(d)] + _decimals[i];
}
}
}
if (decimal == ""||Number(decimal)==0) {
outChars += '整';
}
return outChars;
}
</script>
</head>
<body>
</body>
</html>