瘋狂java課後習題:把浮點數轉化成字串
阿新 • • 發佈:2019-01-28
這是那本書我自己做的作業,基本實現了功能,但實現方式大家可以交流下,我是很多地方圖了個方便
public class NumtoRmb { private String[] hanArr = {"零", "壹", "貳", "叄", "肆", "伍", "律", "柒", "捌", "玖"}; private String[] unitArr = {"", "十", "百", "千"}; //方便後面新增單位浪費多一個數組 private String[] weiArr = {"億", "萬", "元"}; private double num; private String integer; //整數部分 private String decimal; //小數部分 private String[] saveint = {"", "", ""}; //整數部分4個位一組存進數組裡 private String[] showint= {"", "", ""}; //儲存轉換為中文後整數部分的字串陣列 private String showdec; //轉化成中文後的小數部分字串 public void show(double num) { this.num = num; divide(); //num分成整數和小數部分 toDecStr(); //處理小數部分 divInteger(); //把數字4個一組分組分別儲存到一個數組中 toHanStr(); //整數部分轉化成中文 System.out.println(showint[0] + showint[1] + showint[2] + showdec); } private void divide() //num分成整數和小數部分 { long zheng = (long)num; long xiao = Math.round((num - zheng) * 100); integer = zheng + ""; decimal = xiao + ""; // System.out.println(integer + " " + decimal); } private void toDecStr() //處理小數部分 { if(decimal.length() < 2) //如果小數小於2,證明num的情況可能是3456 或者 3456.05這種特殊數字,小數部分就要特殊處理 { int index = decimal.charAt(0) - 48; if(index == 0) showdec = "整"; else showdec ="零" + hanArr[index] + "分"; } else { int index = decimal.charAt(0) - 48; showdec = hanArr[index] + "角"; index = decimal.charAt(1) - 48; showdec += hanArr[index] + "分"; } // System.out.println(showdec); } private void toHanStr() //整數部分轉化成中文 { for(int i = 0; i< 3; i++) { // boolean doubleZer0 = true; boolean lastZero = false; int index; if(saveint[i].length() == 0) //陣列為空,跳過繼續處理下一陣列 continue; for(int j = saveint[i].length(), k =0 ; j>0; j--, k++) { index = saveint[i].charAt(j - 1) - 48; if(index != 0) //特殊處理中間的連續的0,和尾數是0的情況,由於最多是4位數,所以處理還算簡單 lastZero =true; if(index != 0 ) { showint[i] = hanArr[index] + unitArr[k] + showint[i]; } else if(lastZero == true) { showint[i] = hanArr[index] +showint[i]; lastZero = false; } } showint[i] += weiArr[i]; } // System.out.println(showint[0] + " " + showint[1] + " " + showint[2]); } private void divInteger() //把數字4個一組分組分別儲存到一個數組中 { int i = integer.length() ; int j=2, z=0; while(i != 0) { saveint[j] = integer.charAt(i-1) + saveint[j]; // System.out.println(integer.charAt(i-1) + " " + showint[j]); z++; if(z == 4) { j--; z = 0; } i--; } //System.out.println(saveint[0] + " " + saveint[1] + " " + saveint[2]); } public static void main(String[] args) { NumtoRmb nr = new NumtoRmb(); nr.show(42260003246.0); } }