数字金额转汉字
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayDeque;
import java.util.Deque;
public class MoneyTransferHelper {
private static final String[] NUM = { "零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖" };
private static final String[] UNIT = { "分", "角", "元", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟" };
private static final String ZERO = "0";
private static Deque<String> stack = new ArrayDeque<>();
/** 将金额转换为汉字 **/
public static String transferToChinese(Long amount) {
String[] money = amount.toString().split("");
StringBuilder builder = new StringBuilder();
int j = 0;
boolean addZero = false;
for (int i = money.length - 1; i > 0; i--) {
if (ZERO.equals(money[i])) {
//当当前单位为元或万或亿的时候,加入栈中
if (j == 2 || j == 6 || j == 10) {
stack.push(UNIT[j]);
} else if (addZero) {
//加零
stack.push(NUM[0]);
//连续遇到几个0,只需加一次即可
addZero = false;
}
//跳过0的时候,单位指针也要继续往后移动
j++;
continue;
}
//do not use isEmpty to judge this stack is empty,it will let the result be wrong.
if (stack.size() != 0) {
builder.append(stack.pop());
}
addZero = true;
builder.append(UNIT[j++]).append(NUM[Integer.valueOf(money[i])]);
}
return StringUtils.reverse(builder.toString());
}
}