最近看到很多人都问 如何写一个数字转大写的程序,也就是把"123456789"转为 壹亿贰千叁百肆十伍万陆千柒百捌十玖 的程序,很多人都只提供代码,不提供解释,我这里自己也写了一个,有不足之处请大家提出:
import
java.io.
*
;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif)
class
upper
...
{
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
public static void main(String[] args) throws IOException...{
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
String[] big=new String[]...{"零","壹","贰","叁","肆","伍","陆","柒","捌","玖","拾"};
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
String[] bit=new String[]...{"","十","百","千","万","十万","百万","千万","亿"};
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入要转换的数字:");
String rl=br.readLine();
//取数字的位数
int weishu=rl.length() ;
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
if(weishu>9)...{
System.out.println("超出计算范围");
}
//创建StringBuffer 来存储结果
StringBuffer result=new StringBuffer();
//把数字转换成StringBuffer
StringBuffer sb=new StringBuffer(rl);
//反转数字
sb=sb.reverse();
//再转换成int
int rl1=sb2int(sb);
//建立循环
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
for(int i=0;i<rl.length();i++)...{
//数字取余数 %10
int tmp2=rl1%10;
//数字减去最后一位
rl1-=tmp2;
//数字除以10
rl1=rl1/10;
//位数减1
weishu-=1;
//存到结果里
result=result.append(big[tmp2]+bit[weishu]);
}
System.out.print("输出大写为:");
String rs=result.toString();
System.out.println(prossstr(rs));
}
//静态方法,把StringBuffer转换成Int
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
static int sb2int(StringBuffer sb)...{
String tmp=new String(sb);
int tmp2=Integer.parseInt(tmp);
return tmp2;
}
//处理结果
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
static String prossstr(String result)...{
//处理万到亿之间的数
int lg=result.length();
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
if(lg!=0&&lg>9&&lg<19)...{
result=result.replaceAll("万","");
StringBuffer sbresult=new StringBuffer(result);
sbresult=sbresult.reverse();
sbresult=sbresult.insert(7,'万');
sbresult=sbresult.reverse();
return sbresult.toString();
//处理亿以上
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
}else if(lg!=0&&lg>19)...{
result=result.replaceAll("万","");
result=result.replaceAll("亿","");
StringBuffer sbresult=new StringBuffer(result);
sbresult=sbresult.reverse();
sbresult=sbresult.insert(7,'万');
sbresult=sbresult.insert(15,'亿');
sbresult=sbresult.reverse();
return sbresult.toString();
}
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)
else...{
return result;
}
}
}