人民币大写转换实现(一)

2014-11-24 02:29:20 · 作者: · 浏览: 0

Java代码
public class RmbCapitalFormatter {

//大写对应数组
private static final String RMB_CAPITAL[] = {
"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", "拾"
};

private static final HashMap RMB_CAPITAL_MAP = new HashMap();
static {
RMB_CAPITAL_MAP.put("零", 0);
RMB_CAPITAL_MAP.put("壹", 1);
RMB_CAPITAL_MAP.put("贰", 2);
RMB_CAPITAL_MAP.put("叁", 3);
RMB_CAPITAL_MAP.put("肆", 4);
RMB_CAPITAL_MAP.put("伍", 5);
RMB_CAPITAL_MAP.put("陆", 6);
RMB_CAPITAL_MAP.put("柒", 7);
RMB_CAPITAL_MAP.put("捌", 8);
RMB_CAPITAL_MAP.put("玖", 9);
RMB_CAPITAL_MAP.put("拾", 10);
}

//是圆(复)还是元(简)
private boolean isSimpleYuan = false;

//是整(复)还是正(简)
private boolean isSimpleZheng = false;

public RmbCapitalFormatter() {
}

public boolean isSimpleYuan() {
return isSimpleYuan;
}

public void setSimpleYuan(boolean isSimpleYuan) {
this.isSimpleYuan = isSimpleYuan;
}

public boolean isSimpleZheng() {
return isSimpleZheng;
}

public void setSimpleZheng(boolean isSimpleZheng) {
this.isSimpleZheng = isSimpleZheng;
}

public String format(Double data) {
StringBuilder buf = new StringBuilder();
boolean isNegative = false;
if (data < 0) {
isNegative = true;
data = 0 - data;
}
//整数部分
long intPart = data.longValue();
//小数部分,只有前两位小数有意义

int fractionPart = (int)((data - intPart) * 100);
if (intPart == 0 && fractionPart == 0) {
return "人民币零圆整";
}

String cur = "";
boolean needZero = false;
//亿为一个大循环,四位数是一个小循环
while(intPart > 0) {
int lowestFourDigits = (int)(intPart % 10000);
intPart = intPart / 10000;

if (lowestFourDigits > 0) {
if (needZero) {
buf.insert(0, "零");
needZero = false;
}
buf.insert(0, changeFourDigists(lowestFourDigits) + cur);
if (lowestFourDigits < 1000) {
needZero = true;
}
} else {
if ("亿".equals(cur)) {
buf.insert(0, cur);
}
}
if (cur.length() == 0) {
cur = "万";
} else if ("万".equals(cur)) {
cur = "亿";
} else if ("亿".equals(cur)) {
cur = "万";
}
}
if (data > 1) {
if (isSimpleYuan) {
buf.append("元");
} else {
buf.append("圆");
}
}
if (fractionPart > 0) {
int jiaoPart = fractionPart / 10;
int fenPart = fractionPart % 10;
if (jiaoPart > 0) {
buf.append(RMB_CAPITAL[jiaoPart]).append("角");
}
if (fenPart > 0) {
if (data > 1 && jiaoPart == 0) {
buf.append(RMB_CAPITAL[0]);// 零
}
buf.append(RMB_CAPITAL[fenPart]).append("分");
}
} else {
if (isSimpleZheng) {
buf.append("正");