/**
* 金额转换为汉字大写。最大数值99999999999.99
* @param currencyDigits
* @return
*/
public static String convertCurrency(String currencyDigits) {
currencyDigits=currencyDigits.replace(",","");
String MAXIMUM_NUMBER = "99999999999.99";
String CN_ZERO = "零";
String CN_ONE = "壹";
String CN_TWO = "贰";
String CN_THREE = "叁";
String CN_FOUR = "肆";
String CN_FIVE = "伍";
String CN_SIX = "陆";
String CN_SEVEN = "柒";
String CN_EIGHT = "捌";
String CN_NINE = "玖";
String CN_TEN = "拾";
String CN_HUNDRED = "佰";
String CN_THOUSAND = "仟";
String CN_TEN_THOUSAND = "万";
String CN_HUNDRED_MILLION = "亿";
String CN_SYMBOL = "";
String CN_DOLLAR = "元";
String CN_TEN_CENT = "角";
String CN_CENT = "分";
String CN_INTEGER = "整";
int zeroCount;
String d;
currencyDigits = currencyDigits.toString();
if ("".equals(currencyDigits)) {
//金额不能为空
return "金额不能为空";
}
if (1 == new BigDecimal(currencyDigits).compareTo(new BigDecimal(MAXIMUM_NUMBER))) {
//金额过大,应小于1000亿元
return "金额过大,应小于1000亿元";
}
String parts[] = currencyDigits.split("[.]");
String integral;
String decimal;
if (parts.length > 1) {
integral = parts[0];
decimal = parts[1];
if(decimal.length()>1){
decimal = decimal.substring(0, 2);
}else{
decimal = decimal.substring(0, 1);
}
}
else {
integral = parts[0];
decimal = "";
}
String[] digits = {CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE};
String[] radices = {"", CN_TEN, CN_HUNDRED, CN_THOUSAND};
String[] bigRadices = {"", CN_TEN_THOUSAND, CN_HUNDRED_MILLION};
String[] decimals = {CN_TEN_CENT, CN_CENT};
String outputCharacters = "";
if (1 == new BigDecimal(integral).compareTo(new BigDecimal(0))) {
zeroCount = 0;
for (int i = 0; i < integral.length(); i++) {
int p = integral.length() - i - 1;
d = integral.substring(i, i+1);
int quotient = p / 4;
int modulus = p % 4;
if ("0".equals(d)) {
zeroCount++;
}
else {
if (zeroCount > 0)
{
outputCharacters += digits[0];
}
zeroCount = 0;
outputCharacters += digits[Integer.parseInt(d)] + radices[modulus];
}
if (modulus == 0 && zeroCount < 4) {
outputCharacters += bigRadices[quotient];
zeroCount = 0;
}
}
outputCharacters += CN_DOLLAR;
}
if (!"".equals(decimal)) {
for (int i = 0; i < decimal.length(); i++) {
d = decimal.substring(i, i+1);
if (!"0".equals(d)) {
outputCharacters += digits[Integer.parseInt(d)] + decimals[i];
}
}
}
if ("".equals(outputCharacters)) {
outputCharacters = CN_ZERO + CN_DOLLAR;
}
if ("".equals(decimal)) {
outputCharacters += CN_INTEGER;
}
outputCharacters = CN_SYMBOL + outputCharacters;
return outputCharacters;
}
/**
* 测试数字转换为人民币大写
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
Scanner sc = new Scanner(System.in);
while(true){
System.out.print("请输入需要转换的数字:");
String i = sc.nextLine();
System.out.println(convertCurrency(i));
}
}
java中金额转换为汉字大写
最新推荐文章于 2025-06-13 00:15:00 发布
