package org.sz.basic;
import java.text.DecimalFormat;
public class ConvertMoney {
private final static String[] STR_NUMBER = { "零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖" };
private final static String[] STR_UNIT = { "", "拾", "佰", "仟", "万", "拾万",
"佰万", "仟万", "亿", "拾亿", "佰亿", "仟亿" };
private final static String[] STR_UNIT2 = {"厘", "分", "角"};
public static String convert(double money) {
DecimalFormat df = new DecimalFormat("#0.000");
String strMoney = df.format(money);
String point = "";
if (strMoney.indexOf(".") != -1) {
String integer = strMoney.substring(0, strMoney.indexOf("."));
checkIntegerLength(integer);
String decimal = strMoney.substring(strMoney.indexOf(".") + 1);
point = "元";
return convertInteger(integer) + point + convertDecimal(decimal);
} else {
checkIntegerLength(strMoney);
point = "元整";
return convertInteger(strMoney) + point;
}
}
private static void checkIntegerLength(String integer) {
if (integer.length() > 12)
throw new RuntimeException("数字过大不可转换!");
}
private static String convertInteger(String integer) {
return appendUnit((replaceNum(integer, STR_NUMBER)), STR_UNIT);
}
private static String convertDecimal(String decimal) {
return appendUnit((replaceNum(decimal, STR_NUMBER)), STR_UNIT2);
}
/**
* 将小写数字替换成大写数字
*/
private static String replaceNum(String money, String[] number) {
char[] _money = money.toCharArray();
String result = "";
for (int i = 0; i < _money.length; i++) {
int index = Integer.valueOf(_money[i] + "");
result += number[index];
}
return result;
}
/**
* 为大写数字添加单位
*/
private static String appendUnit(String money, String[] unit) {
char[] _money = money.toCharArray();
String result = "";
String previousNum = "";
String currentNum = "";
for (int i = 0; i < money.length(); i++) {
currentNum = _money[i] + "";
if (i > 0) {
previousNum = _money[i - 1] + "";
}
//中间连续的0只保留一个
if (previousNum.equals("零") && currentNum.equals("零")) {
continue;
} else if(i != money.length() && currentNum.equals("零")) {
result += _money[i];
} else {
result += (_money[i] + unit[money.length() - i - 1]);
}
}
System.out.println(handlerZero(result));
return handlerZero(result);
}
private static String handlerZero(String result) {
int last = result.lastIndexOf("零");
if (last == result.length() - 1) {
result = result.substring(0, last);
}
return result;
}
public static void main(String[] args) {
convert(30000010000.001);
}
}
金额转换为中文大写格式
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.