欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

人民币金额数字转中文大写程序多种编程语言汇总2011版

程序员文章站 2022-05-11 08:29:44
...

        这里目前给大家提供的是PHP,JSP(JAVA),ASP(VB6),JAVASCRIPT,VC++,Python,ActionScript3.0, VB.Net,C#  等语言的版本.

        网上搜索一下:你要的编程语言名称,再加上“人民币 数字 金额 转大写 汉字”,结果就会出来异常多的结果。所以,这种代码已相当烂了,到处都有。什么语言的都有。到处都有的代码,你为什么要重造*?没办法呀,我实在不能用那些无法维护的代码。尽管我的代码写得不算是最好的,但总要有一个象样的代码,我才安心!!
        很多人都在讲程序高手。其实高手就在于相当简单的基本功上。比如,你的for循环用得如何?你的if用得怎样。当然,早年用VB的人,if用得肯定好。因为,VB没有continue,你不得不反向思维,写好if。
        其实高手还有另一个关键点,那就是程序如何写。所有高手都擅长预处理数据,从而使得程序不会跟着数据跑。在这一前提下,任何一个问题,众多高手的写出来的代码流程均是相似的。而普通程序员则会千差万别。
        比如现在网上的人民币金额转大写程序,任何语言,你都不能找到一个满意的版本。也有人甚至说,这个算法,绝对不可能在30行以内完成(指PHP)。
        好久不写其它编程语言的代码了,接下来,会用到这样的程序。所以,作为一个伪高手,技术不是怎样的我,写出一个版本,PHP代码竟然只有21行。所以,决定分享给大家。觉得给初学者指一个路,看看if, for该当如何使用。(从PHP说,这个代码中如果if用不好,则会多出几个continue和至少一个break。另外,如果不注意使用数学方法,与预定义变量的配置,还会多出好几个if,当然,这并不算优秀的代码,仅供参考!!)
        其实,如果你仔细看一下代码,你就会发现,经过数据预处理后,将算法中有if全部集中起来了,并且能将其嵌入到循环中了。由此可见,先将数据处理成程序方便处理的格式,程序中就会少掉大量的代码。预处理数据后,程序不会跟着数据走。这一点在我公开课《数据处理算法设计要点》(链接中的网址是首发网址,百度文库未经许可,属于抄袭。当然,这个盗版人稍有一点人性,不象《PHP程序员必须掌握的PHP面向对象的特有的特性》盗版人,抹去了所有原作者去出处信息!!)中已经讲过。有心人可以在网上搜索到。所以,不多讲了。

        另外有一点,我们可以看出,PHP的代码行数是最少的。用好了PHP的人都了解,远比JAVA精简多了。比如,本函数中的数据预处理,PHP因为拥有sprintf,因而仅需一行代码。但JAVA却绕了相当大的弯子。从这一点来讲,PHP是造就优秀程序员的语言。而JAVA则是让傻瓜使用的语言。VB就更不用说了,完全是面对门外汉的。(个人看法,不用当真。当真你就输了!)

        其次,很多版本的,真正按汉语习惯,或者说真正按数字读法完全正确的写出的并不多。比如,302000,应当是叁拾万贰仟。但却有叁拾万零贰仟的版本。而300200应当是叁拾万零贰佰,却也有叁拾万贰佰的版本。所以,写代码的人,首先对汉语数字正确的读法都不清楚。
        这个函数是支持16位整数的。但是对于万亿,仍用的是万,因为,无法用兆,兆在当今是10的6次方,不再是12次方了。如果你不习惯,直接将第一个万改成万亿即可。
        要注意的是,32位机中,大数字会溢出,对于PHP,直接传入字串形式的测试。
        当然,目前还缺象C++,  Ruby的版本。如果有有兴趣完成,别忘了发给我,我会加进来,当然,程序中一定是暑你的大名了。

        网上代码,搜索出来的是什么样子?看一看好心人保存下来的我在2002年完成的代码大家可能就了解了。虽然,函数使用,流程处理的功夫上已不低,但还没有懂得,如何进行预处理。程序是完全跟着数据走的。那时,在大家看来是最好的VB代码了。可现在我看,仍然是很差的代码,因为,同下面现在写的代码比一下,行数更少。程序逻辑更加清析。2002年的代码的网址如下:

        http://topic.csdn.net/t/20020802/11/918115.html
        以下是各编程语言的代码。(注:Python代码于2011年4月17日最后修改)
        版权声明:
Copyright (c) 2010 Bardo QI

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

 

Php代码 
//人民币金额转大写程序 PHP版   
//CopyRight Bardo QI   
  
function numToCny($num){   
    $capUnit=array('万','亿','万','圆','');   
    $capDigit=array(2=>array('角','分',''), 4=>array('仟','佰','拾',''));   
    $capNum=array('零','壹','贰','叁','肆','伍','陆','柒','捌','玖');   
    if ((strpos(strval($num),'.')>16)||(!is_numeric($num)))   
        return '';   
    $num = sprintf("%019.2f",$num);   
    $CurChr=array('','');   
    for ($i=0,$ret='',$j=0;$i<5;$i++,$j=$i*4+floor($i/4)){   
        $nodeNum=substr($num,$j,4);   
        for($k=0,$subret='',$len=strlen($nodeNum);(($k<$len)&&(intval(substr($nodeNum,$k))!=0));$k++){   
            $CurChr[$k%2] = $capNum[$nodeNum{$k}].(($nodeNum{$k}==0)?'':$capDigit[$len][$k]);   
            if (!(($CurChr[0]==$CurChr[1]) && ($CurChr[$k%2]==$capNum[0])))   
                if(!(($CurChr[$k%2] == $capNum[0]) && ($subret=='') && ($ret=='')))   
                    $subret .= $CurChr[$k%2];   
        }   
        $subChr = $subret.(($subret=='')?'':$capUnit[$i]);   
        if(!(($subChr == $capNum[0]) && ($ret=='')))   
            $ret .= $subChr;   
    }   
    $ret=($ret=="")?$capNum[0].$capUnit[3]:$ret;       
    return $ret;   
}  

 

//人民币金额转大写程序 JavaScript版   
//CopyRight Bardo QI   
  
function numToCny(num){   
    var capUnit = ['万','亿','万','圆',''];   
    var capDigit = { 2:['角','分',''], 4:['仟','佰','拾','']};   
    var capNum=['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];   
    if (((num.toString()).indexOf('.') > 16)||(isNaN(num)))    
        return '';   
    num = ((Math.round(num*100)).toString()).split('.');
 num = (num[0]).substring(0, (num[0]).length-2)+'.'+ (num[0]).substring((num[0]).length-2,(num[0]).length);
    num =((Math.pow(10,19-num.length)).toString()).substring(1)+num;   
    var i,ret,j,nodeNum,k,subret,len,subChr,CurChr=[];   
    for (i=0,ret='';i<5;i++,j=i*4+Math.floor(i/4)){   
        nodeNum=num.substring(j,j+4);   
        for(k=0,subret='',len=nodeNum.length;((k<len) && (parseInt(nodeNum.substring(k),10)!=0));k++){   
            CurChr[k%2] = capNum[nodeNum.charAt(k)]+((nodeNum.charAt(k)==0)?'':capDigit[len][k]);   
            if (!((CurChr[0]==CurChr[1]) && (CurChr[0]==capNum[0])))   
                if(!((CurChr[k%2] == capNum[0]) && (subret=='') && (ret=='')))   
                    subret += CurChr[k%2];   
        }   
        subChr = subret + ((subret=='')?'':capUnit[i]);   
        if(!((subChr == capNum[0]) && (ret=='')))   
            ret += subChr;   
    }   
    ret=(ret=='')? capNum[0]+capUnit[3]: ret;     
    return ret;   
} 

 

'人民币金额转大写程序 Asp、 Vb6版   
'CopyRight Bardo QI   
  
Function numToCny(num)   
    capUnit = Array("万", "亿", "万", "圆", "")   
    capDigit = Array(Array(), Array(), Array("角", "分", ""), Array(), Array("仟", "佰", "拾", ""))   
    capNum = Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖")   
    If (((InStr(1, num, ".") > 16) Or (Not IsNumeric(num)))) Then   
        numToCny = ""  
        Exit Function   
    End If   
    num = FormatNumber(num, 2, , , 0)   
    num = Mid(CStr(10 ^ (19 - Len(num))), 2) + num   
    CurChr = Array("", "")   
    ret = ""  
    For i = 0 To 4  
        j = i * 4 + Int(i / 4) + 1  
        nodeNum = Mid(num, j, 4)   
        slen = Len(nodeNum)   
        subret = ""  
        For k = 1 To slen   
            If Int(Mid(nodeNum, k)) = 0 Then   
                Exit For   
            End If   
            CurChr(k Mod 2) = capNum(Int(Mid(nodeNum, k, 1))) + IIf(Int(Mid(nodeNum, k, 1)) = 0, "", capDigit(slen)(k - 1))   
            If (Not ((CurChr(0) = CurChr(1)) And (CurChr(0) = capNum(0)))) Then   
                If (Not ((CurChr(k Mod 2) = capNum(0)) And (subret = "") And (ret = ""))) Then   
                    subret = subret + CurChr(k Mod 2)   
                End If   
            End If   
        Next   
        subChr = subret + IIf((subret = ""), "", capUnit(i))   
        If (Not ((subChr = capNum(0)) And (ret = ""))) Then   
            ret = ret + subChr   
        End If   
    Next   
    ret=Iif((ret=""), capNum(0)+capUnit(3), ret)    
    numToCny = ret   
End Function  

 

 

//人民币金额转大写程序 jsp, Java版
//CopyRight Bardo QI
//警告,因为未装JAVA编译器,所以,这一代码未经测试!
import java.util.ArrayList;
import java.util.Math.*;
import java.lang.*;
String numToCny(String num){
    String capUnit[] ={"万","亿","万","圆",""};
    String capDigit[][] = { {""},{""},{"角","分",""},{""},{"仟","佰","拾",""}};
    String capNum[]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};

    if (num.indexOf(".") > 16)
        return "ERROR";
    double dnum=Double.parseDouble(num);
    dnum = Math.round(dnum*100)/100;
    if (Double.isNaN(dnum))
        return "ERROR";
    String snum = Double.toString(dnum);
    double pnum = Math.pow(10,19-snum.length());
    String psnum = Double.toString(pnum);
    snum = psnum.substring(1)+snum;
    String ret,nodeNum,subret,subChr;
    ArrayList CurChr = new ArrayList(2);
    int i,j,k,len;
    for (i=0,ret="";i<5;i++,j=i*4+(int)Math.floor(i/4)){
        nodeNum=snum.substring(j,j+4);
        for(k=0,subret="",len=nodeNum.length();((k<len) && (Integer.parseInt(nodeNum.substring(k))!=0));k++){
            CurChr.set(k%2,capNum[Integer.parseInt(nodeNum.substring(k,k+1))]+((nodeNum.substring(k,k+1).equals("0"))?"":capDigit[len][k]));
            if (!((CurChr.get(0)==CurChr.get(1)) && (CurChr.get(0)==capNum[0])))
                if(!((CurChr.get(k%2) == capNum[0]) && (subret.equals(""))  && (ret.equals(""))))
                    subret += CurChr.get(k%2);
        }
        subChr = subret + ((subret.equals(""))?"":capUnit[i]);
        if(!((subChr == capNum[0]) && (ret.equals(""))))
            ret += subChr;
    }
    ret=(ret.equals(""))? capNum[0]+capUnit[3]: ret;
    return ret;
}

 

 

//人民币金额转大写程序VC++版   
//CopyRight Bardo QI   
  
CString numtoCny(double Num)   
{   
    char* capUnit[]={"万","亿","万","圆",""};   
    char* capDigit[5][4]={{""},{""},{"角","分",""},{""},{"仟","佰","拾",""}};   
    char* capNum[]={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};   
    CString num,ret="",nodeNum="",subret,subChr,thisChr,lastChr,ch;   
    num.Format("%019.2f",Num);   
    if(num.Find(".")>16)   
        return ret;   
    int i,j,k,len,chn;   
    for (i=0;i<5;i++,j=i*4+int(i/4)){   
        nodeNum= num.Mid(j,4);   
        subret="";   
        lastChr="";   
        for(k=0,len=nodeNum.GetLength();((k<len)&&(atoi((LPCTSTR)nodeNum.Mid(k,4-k))!=0));k++){   
            ch= nodeNum[k];   
            chn=atoi((LPCTSTR)ch);   
            thisChr = capNum[chn] ;   
            thisChr += (chn==0) ? "" : capDigit[len][k];   
            if (!((thisChr==lastChr) && (thisChr==capNum[0])))   
                if(!((thisChr == capNum[0]) && (subret=="") && (ret=="")))   
                    subret += thisChr;   
            lastChr=thisChr;   
        }   
        subChr = subret;   
        subChr += (subret=="")?"":capUnit[i];   
        if(!((subChr == capNum[0]) && (ret=="")))   
            ret += subChr;   
    }   
    (ret=="")?ret.Format("%s%s",capNum[0],capUnit[3]):ret;    
    return ret;   
}  

 

#人民币金额转大写程序Python版本      
#Copyright: zinges at foxmail.com       
#blog: http://zingers.iteye.com     
#感谢zinges提供了Python的版本     
import math   
def numtoCny(num):   
    capUnit = ['万','亿','万','圆','']   
    capDigit = { 2:['角','分',''], 4:['仟','佰','拾','']}   
    capNum=['零','壹','贰','叁','肆','伍','陆','柒','捌','玖']   
    snum = str('%019.02f') % num   
    if snum.index('.')>16:   
        return ''  
    ret,nodeNum,subret,subChr='','','',''  
    CurChr=['','']   
    for i in range(5):   
        j=int(i*4+math.floor(i/4))   
        subret=''  
        nodeNum=snum[j:j+4]   
        lens=len(nodeNum)   
        for k in range(lens):   
            if int(nodeNum[k:])==0:   
                continue  
            CurChr[k%2] = capNum[int(nodeNum[k:k+1])]   
            if nodeNum[k:k+1] != '0':   
                CurChr[k%2] += capDigit[lens][k]   
            if  not ((CurChr[0]==CurChr[1]) and (CurChr[0]==capNum[0])):   
                if not((CurChr[k%2] == capNum[0]) and (subret=='') and (ret=='')):   
                    subret += CurChr[k%2]   
        subChr = [subret,subret+capUnit[i]][subret!='']   
        if not ((subChr == capNum[0]) and (ret=='')):   
            ret += subChr   
    return [ret,capNum[0]+capUnit[3]][ret=='']  

 

//人民币金额转大写程序 ActionScript 3.0版   
//CopyRight Bardo QI   
  
public function numToCny(num:String):String{   
    var capUnit:Array =['万','亿','万','圆',''];   
    var capDigit:Array = [[],[], ['角','分',''],[], ['仟','佰','拾','']];   
    var capNum:Array=['零','壹','贰','叁','肆','伍','陆','柒','捌','玖'];   
    if ((num.indexOf('.') > 16)||(isNaN(parseFloat(num))))    
        return '';   
    var dnum:Number = Math.round(parseFloat(num)*100)/100;    
    num = dnum.toString();   
    var inum:Number = Math.pow(10,19-num.length);    
    var pnum:String = inum.toString();   
    num = pnum.substring(1)+num;   
    var i:Number,ret:String,j:Number,nodeNum:String,k:Number,subret:String,len:Number,subChr:String,CurChr:Array=['',''];   
    for (i=0,ret='';i<5;i++,j=i*4+Math.floor(i/4)){   
        nodeNum=num.substring(j,j+4);   
        for(k=0,subret='',len=nodeNum.length;((k<len) && (parseInt(nodeNum.substring(k))!=0));k++){   
            CurChr[k%2] = capNum[parseInt(nodeNum.charAt(k))]+((nodeNum.charAt(k)=='0')?'':capDigit[len][k]);   
            if (!((CurChr[0]==CurChr[1]) && (CurChr[0]==capNum[0])))   
                if(!((CurChr[k%2] == capNum[0]) && (subret=='') && (ret=='')))   
                    subret += CurChr[k%2];   
        }   
        subChr = subret + ((subret=='')?'':capUnit[i]);   
        if(!((subChr == capNum[0]) && (ret=='')))   
            ret += subChr;   
    }   
    ret=(ret=='')? capNum[0]+capUnit[3]: ret;     
    return ret;   
}  

 

'人民币金额转大写程序 VB.Net版   
    'CopyRight Bardo QI   
  
    Function numToCny(ByVal num)   
        Dim capUnit() As String = {"万", "亿", "万", "圆", ""}   
        Dim capDigit(,) As String = {{"", "", "", ""}, {"", "", "", ""}, {"角", "分", "", ""}, {"", "", "", ""}, {"仟", "佰", "拾", ""}}   
        Dim capNum() As String = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}   
        If (((InStr(1, num, ".") > 16) Or (Not IsNumeric(num)))) Then   
            numToCny = ""  
            Exit Function   
        End If   
        num = FormatNumber(num, 2, , , 0)   
        num = Mid(CStr(10 ^ (19 - Len(num))), 2) + num   
        Dim CurChr() = {"", ""}, nodeNum As String, subret As String, subChr As String, slen As Integer, i As Integer, j As Integer, k As Integer   
        Dim ret As String = ""  
        For i = 0 To 4  
            j = i * 4 + Int(i / 4) + 1  
            nodeNum = Mid(num, j, 4)   
            slen = Len(nodeNum)   
            subret = ""  
            For k = 1 To slen   
                If Int(Mid(nodeNum, k)) = 0 Then   
                    Exit For   
                End If   
                CurChr(k Mod 2) = capNum(Int(Mid(nodeNum, k, 1))) + IIf(Int(Mid(nodeNum, k, 1)) = 0, "", capDigit(slen, k - 1))   
                If (Not ((CurChr(0) = CurChr(1)) And (CurChr(0) = capNum(0)))) Then   
                    If (Not ((CurChr(k Mod 2) = capNum(0)) And (subret = "") And (ret = ""))) Then   
                        subret = subret + CurChr(k Mod 2)   
                    End If   
                End If   
            Next   
            subChr = subret + IIf((subret = ""), "", capUnit(i))   
            If (Not ((subChr = capNum(0)) And (ret = ""))) Then   
                ret = ret + subChr   
            End If   
        Next   
        numToCny = IIf((ret = ""), capNum(0) + capUnit(3), ret)   
    End Function  

  

        //人民币金额转大写程序C#版
        //CopyRight Bardo QI
        string numtoCny(decimal Num){
	        string[] capUnit = {"万","亿","万","圆",""};
            string[,] capDigit = { { "", "", "", "" }, { "", "", "", "" }, { "角", "分", "", "" }, { "", "", "", "" }, { "仟", "佰", "拾", "" } };   
	        string[] capNum = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
            string num, ret = "", nodeNum = "", subret, subChr;
            string[] thisChr={"",""};
            num = String.Format("{0:0000000000000000.00}",Num);
            if(num.IndexOf(".")>16)
	            return ret;
            int i,j,k,len,ch;
            for (i=0,j=0;i<5;i++,j=i*4 + int.Parse(Math.Floor((double)i/4).ToString()) ){
                len = (j < 17) ? 4 : 2;
                nodeNum = num.Substring(j, len);
	            subret="";
                for (k = 0; ((k < len) && (int.Parse(nodeNum.Substring(k, len - k)) != 0)); k++){
                    ch = int.Parse(nodeNum.Substring(k, 1));
                    thisChr[i%2] = capNum[ch];
                    thisChr[i % 2] += (ch == 0) ? "" : capDigit[len,k];
                    if (!((thisChr[0] == thisChr[1]) && (thisChr[i % 2] == capNum[0])))
                        if (!((thisChr[i % 2] == capNum[0]) && (subret == "") && (ret == "")))
                            subret += thisChr[i % 2];
                }
                subChr = subret;
	            subChr += (subret=="")?"":capUnit[i];
	            if(!((subChr == capNum[0]) && (ret=="")))
    	            ret += subChr;
            }
            ret=(ret=="")? capNum[0]+capUnit[3]:ret;
            return ret;
        }
    }

 

 

版权声明:本文是作者版权文章,未经作者以及javaeye的许可不得转载!特别声明:禁止百度文库恶意转载的剽窃行径!!

更新提示:Java版的代码己经过TextPad编译通过。