傻瓜版
写到最后懒得写小数部分了,反正逻辑都是一样绕。
package chapter4; public class FloatToRmb { public static void main(String[] args) { double f = 1006.789; String[] ds = num(f); String begin = ds[0]; String after = ds[1]; String str = ""; if (begin.length() > 0) str = handleBefore(begin); if (after.length() > 0) { str = str + handleAfter(after); } System.out.println(str); } public static String handleBefore(String str) {// 1006 String str1 = ""; if (str.length() > 0) {// 2{ if (!str.substring(str.length() - 1).equals("0"))// 6 str1 = str.substring(str.length() - 1) + "元"; str = str.substring(0, str.length() - 1); System.out.println(str.length()); } if (str.length() > 0) {// 2 if (!str.substring(str.length() - 1).equals("0"))// 6 { str1 = str.substring(str.length() - 1) + "shi" + str1; } else { str1 = "零" + str1; } str = str.substring(0, str.length() - 1); } if (str.length() > 0) {// 2 if (!str.substring(str.length() - 1).equals("0"))// 6 { str1 = str.substring(str.length() - 1) + "bai" + str1; } else if (!str1.startsWith("零")) { str1 = "零" + str1; } str = str.substring(0, str.length() - 1); } if (str.length() > 0) {// 2 if (!str.substring(str.length() - 1).equals("0"))// 6 str1 = str.substring(str.length() - 1) + "qian" + str1; } return str1; } public static String toChineseNum(int a) { String str = ""; switch (a) { case 1: str = "壹"; case 2: str = "贰"; case 3: str = "叁"; case 4: str = "肆"; case 5: str = "伍"; case 6: str = "陆"; case 7: str = "柒"; case 8: str = "捌"; case 9: str = "久"; } return str; } public static String handleAfter(String str) { return "2"; } public static String[] num(double d) { String[] ds = { "", "" }; String str = String.valueOf(d); int num = str.indexOf("."); ds[0] = str.substring(0, num); ds[1] = str.substring(num + 1); return ds; } }
改进版
思路想好了
对所有数值,都转换成 xxxxxxx的格式
即 1006 转为 1006000,10067转为1006700 ,6.7转为0006700;
对任意7位数,插入字符
String 1 ="1234567";
String 2 = "千百十元角分毫"
str="1千2百3十4元5分6角7毫";
package chapter4; public class FloatToRmb { public static void main(String[] args) { double d=10.078; int a=(int)(d*1000);//1066789 String str=String.valueOf(a); if(str.length()<=1){ str="零"; } while(str.length()!=7){ str="0"+str; } String str1="千百十元角分毫";//3 String str2=""; for(int i=str.length();i>0;i--){ if(!str.substring(i-1,i).equals("0")){ str2=str.substring(i-1,i)+str1.substring(i-1, i)+str2; }else if (str.substring(i-1,i).equals("0") &&(!str2.startsWith("零")) &&((i-1)<3) &&(!str.startsWith("0")) &&!str2.startsWith("元")//元 ){//indexof 似乎不能识别中文? System.out.println(str1.indexOf("元")+","+(i-1)); str2="零"+str2; }else if(!str2.startsWith("元") &&((i-1)==3)){ str2="元"+str2; } System.out.println(str.substring(i-1, i)); str1=str1.substring(0, i-1); str=str.substring(0, i-1); } System.out.println(str2); } }
逻辑判断的部分太垃圾了。。。。还需要改进