java實現 阿拉伯數字轉換為漢字數字 演算法

來源:互聯網
上載者:User

標籤:

package test;


public class NumberFormatTest {


static String[] units = { "", "十", "百", "千", "萬", "十萬", "百萬", "千萬", "億",
"十億", "百億", "千億", "萬億" };
static char[] numArray = { ‘零‘, ‘一‘, ‘二‘, ‘三‘, ‘四‘, ‘五‘, ‘六‘, ‘七‘, ‘八‘, ‘九‘ };


/**
* @param args
*/
public static void main(String[] args) {
int num = 245000006;
String numStr = foematInteger(num);
print("num= " + num + ", convert result: " + numStr);
double decimal = 245006.234206;
print("============================================================");
String decStr = formatDecimal(decimal);
print("decimal= " + decimal + ", decStr: " + decStr);
}


private static String foematInteger(int num) {
char[] val = String.valueOf(num).toCharArray();
int len = val.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
String m = val[i] + "";
int n = Integer.valueOf(m);
boolean isZero = n == 0;
String unit = units[(len - 1) - i];
if (isZero) {
if (‘0‘ == val[i - 1]) {
// not need process if the last digital bits is 0
continue;
} else {
// no unit for 0
sb.append(numArray[n]);
}
} else {
sb.append(numArray[n]);
sb.append(unit);
}
}
return sb.toString();
}


private static String formatDecimal(double decimal) {
String decimals = String.valueOf(decimal);
int decIndex = decimals.indexOf(".");
int integ = Integer.valueOf(decimals.substring(0, decIndex));
int dec = Integer.valueOf(decimals.substring(decIndex + 1));
String result = foematInteger(integ) + "." + formatFractionalPart(dec);
return result;
}


private static String formatFractionalPart(int decimal) {
char[] val = String.valueOf(decimal).toCharArray();
int len = val.length;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++) {
int n = Integer.valueOf(val[i] + "");
sb.append(numArray[n]);
}
return sb.toString();
}


private static void print(Object arg0) {
System.out.println(arg0);
}
}

java實現 阿拉伯數字轉換為漢字數字 演算法

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.