public class Test10 {
public static String[] cn = { "元", "拾", "佰", "仟", "萬", "拾", "佰", "仟", "亿",
"拾", "佰", "仟", "萬" };
public static String[] number = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒",
"捌", "玖" };
public static void main(String[] args) {
double money = 80101000001010.889;
//将给的double值四舍五入后保留两位小数
DecimalFormat df = new DecimalFormat("#0.00");
String str_money = df.format(money);
//转换格式
String moneyToCN = convert(str_money);
System.out.println(moneyToCN);
}
public static String convert(String str_money) {
String[] s1 = str_money.split("\\.");
String zhengshu = s1[0];
zhengshu = zhengshu.replaceAll(",", "");
String xiaoshu = s1[1];
// 处理整数部分
zhengshu = formatInteger(zhengshu);
// 处理小数部分
xiaoshu = formatDecimals(xiaoshu);
return zhengshu+xiaoshu;
}
//处理小数部分
private static String formatDecimals(String xiaoshu) {
StringBuilder decimals = new StringBuilder();
decimals.append("0.").append(xiaoshu);
String p = decimals.toString().replaceAll("\\.", "");
decimals.delete(0, decimals.length());
for (int x = 0; x < p.length(); x++) {
decimals.append(number[Integer.parseInt(p.charAt(x) + "")]);
}
if (decimals.charAt(1) != '零') {
decimals.insert(2, "角");
if (decimals.charAt(3) != '零') {
decimals.append("分");
}
}else if(decimals.charAt(2) != '零') {
decimals.append("分");
decimals.deleteCharAt(1);
}else{
decimals.delete(0, decimals.length());
decimals.append("整");
}
return decimals.toString();
}
//处理整数部分
private static String formatInteger(String zhengshu) {
StringBuilder integer = new StringBuilder();
for (int x = 0; x < zhengshu.length(); x++) {
integer.append(number[Integer.parseInt(zhengshu.charAt(x) + "")]);
}
integer = integer.reverse();
for (int x = 0, y = 0; x < integer.length() && x < cn.length; x++, y += 2) {
if (y < integer.length())
integer.insert(y, cn[x]);
}
integer = integer.reverse();
zhengshu = integer.toString();
zhengshu = zhengshu.replaceAll("零[仟佰拾]", "零");
zhengshu = zhengshu.replaceAll("零{2,}", "零");
zhengshu = zhengshu.replaceAll("零元", "元");
zhengshu = zhengshu.replaceAll("零([亿萬])", "$1");
zhengshu = zhengshu.replaceAll("亿萬", "亿零");
return zhengshu;
}
}
|
|