运用了正则表达式的功能,除了可以正确的转换成人民币的大写形式以外,还可以判断输入的形式是否正确有效。
将人民币数字转换成大写形式functionconvertCurrency(currencyDigits){//Constants:varMAXIMUM_NUMBER=99999999999.99;//Predefinetheradixcharactersandcurrencysymbolsforoutput:varCN_ZERO="零";varCN_ONE="壹";varCN_TWO="贰";varCN_THREE="叁";varCN_FOUR="肆";varCN_FIVE="伍";varCN_SIX="陆";varCN_SEVEN="柒";varCN_EIGHT="捌";varCN_NINE="玖";varCN_TEN="拾";varCN_HUNDRED="佰";varCN_THOUSAND="仟";varCN_TEN_THOUSAND="万";varCN_HUNDRED_MILLION="亿";varCN_SYMBOL="人民币";varCN_DOLLAR="元";varCN_TEN_CENT="角";varCN_CENT="分";varCN_INTEGER="整";//Variables:varintegral;//Representintegralpartofdigitnumber.vardecimal;//Representdecimalpartofdigitnumber.varoutputCharacters;//Theoutputresult.varparts;vardigits,radices,bigRadices,decimals;varzeroCount;vari,p,d;varquotient,modulus;//Validateinputstring:currencyDigits=currencyDigits.toString();if(currencyDigits==""){alert("Emptyinput!");return"";}if(currencyDigits.match(/[^,.\d]/)!=null){alert("Invalidcharactersintheinputstring!");return"";}if((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/)==null){alert("Illegalformatofdigitnumber!");return"";}//Normalizetheformatofinputdigits:currencyDigits=currencyDigits.replace(/,/g,"");//Removecommadelimiters.currencyDigits=currencyDigits.replace(/^0+/,"");//Trimzerosatthebeginning.//Assertthenumberisnotgreaterthanthemaximumnumber.if(Number(currencyDigits)>MAXIMUM_NUMBER){alert("Toolargeanumbertoconvert!");return"";}//Processthecoversionfromcurrencydigitstocharacters://Separateintegralanddecimalpartsbeforeprocessingcoversion:parts=currencyDigits.split(".");if(parts.length>1){integral=parts[0];decimal=parts[1];//Cutdownredundantdecimaldigitsthatareafterthesecond.decimal=decimal.substr(0,2);}else{integral=parts[0];decimal="";}//Preparethecharacterscorrespondingtothedigits:digits=newArray(CN_ZERO,CN_ONE,CN_TWO,CN_THREE,CN_FOUR,CN_FIVE,CN_SIX,CN_SEVEN,CN_EIGHT,CN_NINE);radices=newArray("",CN_TEN,CN_HUNDRED,CN_THOUSAND);bigRadices=newArray("",CN_TEN_THOUSAND,CN_HUNDRED_MILLION);decimals=newArray(CN_TEN_CENT,CN_CENT);//Startprocessing:outputCharacters="";//Processintegralpartifitislargerthan0:if(Number(integral)>0){zeroCount=0;for(i=0;i