标签:java
代码如下:
<span style="font-size:18px;">package test; import java.util.Scanner; //将输入的浮点型钱数,转成人民币读法 public class Num2Rmb { private static double num; private long zheng,xiao; private String[] hanArr={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"}; private String[] danwei={"千","百","十",""}; private String[] jinwei={"","万","亿"}; private int[][] temp= new int[4][18]; //将输入的钱数,转成小数和整数部分 private void swp(){ zheng=(long)num; xiao=Math.round((num-zheng)*100); } //将整数部分按四位划分成3个部分,不存在的补0 private void divide(){ int i,j,k=0; for(i=0;i<3;i++){ long t1=zheng%10000; int t=(int) t1; zheng=zheng/10000; for(j=3;j>=0;j--){ temp[i][j]=t%10; t=t/10; } } } //检测是否要对当前的四位进行处理 private int check(int i){ for(int j=0;j<4;j++) if(temp[i][j]!=0) return 1; return 0; } //打印结果 private void print(){ //先处理整数部分 //flag用于表示当前部分是否要处理前导0 int i,j,k,flag=0,cnt=0,flag2=0; for(i=2;i>=0;i--){ if(check(i)==0){ if(flag==1&&cnt==0){ System.out.print("零"); cnt++; } flag=0; continue; } //处理前导0 for(j=0;j<4;j++) if(temp[i][j]!=0) break; flag2=1; if(j!=0&&flag==1) System.out.print("零"); int d; //将末尾的0去掉 for(d=3;d>=0;d--) if(temp[i][d]!=0) break; for(k=j;k<=d;k++){ if(temp[i][k]!=0) System.out.print(hanArr[temp[i][k]]+danwei[k]); else if(k-1>=0&&temp[i][k-1]!=0){ System.out.print(hanArr[0]); } } flag=1; System.out.print(jinwei[i]); } if(flag2==1) System.out.print("元"); //处理小数部分 if(xiao/10!=0) System.out.print(hanArr[(int)xiao/10]+"角"); if(xiao%10!=0) System.out.print(hanArr[(int)xiao%10]+"分"); System.out.println(); } //对外的运行接口 public void run(){ swp(); divide(); print(); } public static void main(String[] args){ Scanner sc= new Scanner(System.in); System.out.println("请输入钱数:"); while(sc.hasNext()){ num = sc.nextDouble(); Num2Rmb nr =new Num2Rmb(); /* //调试部分 nr.swp(); System.out.println(nr.zheng+" "+nr.xiao); nr.divide(); for(int i=2;i>=0;i--){ for(int j=0;j<4;j++) System.out.print(nr.temp[i][j]); System.out.println(); } nr.print(); */ nr.run(); System.out.println("请输入钱数:"); } } } </span>
标签:java
原文地址:http://blog.csdn.net/acm_lkl/article/details/41520221