将小写阿拉伯数字转换为大写汉字
广泛应用于银行各种书写情景
代码如下:
import java.text.DecimalFormat;
import java.util.Scanner;
public class ConverMoney {
private final static String[] STR_NUMBER = { "零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖" };
private final static String[] STR_UNIT = { "", "拾", "佰", "仟", "万", "拾",
"佰", "仟", "亿", "拾", "佰", "仟" };// 整数单位
private final static String[] STR_UNIT2 = { "角", "分", "厘" };// 小数单位
public static void main(String[] args){
Scanner inScanner = new Scanner(System.in);
System.out.print("请输入一个数值:");
String c = convert(inScanner.nextDouble());
System.out.println(c);
}
convert函数用于处理输入的数字的整数部分
public static String convert(double d){
DecimalFormat df = new DecimalFormat("#0.###");
String strNumString = df.format(d);
if(strNumString.indexOf(".") != -1){
String num = strNumString.substring(0, strNumString.indexOf("."));
if(num.length()>12){
System.out.println("数字太大不能转换");
return "";
}
}
String point = "";
if(strNumString.indexOf(".")!=-1){
point = "元";
}else{
point = "元整";
}
String result = getInteger(strNumString)+point+getDecimal(strNumString);
if(result.startsWith("元")){
result = result.substring(1,result.length());
}
return result;
}
getInteger函数用于处理小数部分
public static String getInteger(String num){
if(num.indexOf(".")!=-1){
num = num.substring(0,num.indexOf("."));
}
num = new StringBuffer(num).reverse().toString();
StringBuffer tempBuffer = new StringBuffer();
for(int i = 0;i<num.length();i++){
tempBuffer.append(STR_UNIT[i]);
tempBuffer.append(STR_NUMBER[num.charAt(i)-48]);
}
num = tempBuffer.reverse().toString();
num = num.replace("零拾", "零");
num = num.replace("零佰", "零");
num = num.replace("零仟", "零");
num = num.replace("零万", "零");
num = num.replace("零亿", "零");
num = num.replace("零零", "零");
num = num.replace("亿万", "亿");
if(num.lastIndexOf("零")==num.length()-1){
num = num.substring(0,num.length()-1);
}
return num;
}
public static String getDecimal(String num) {
if(num.indexOf(".")!=-1){
num = num.substring(num.indexOf(".")+1, num.length());
}
StringBuffer tempBuffer = new StringBuffer();
for(int i=0;i<num.length();i++){
tempBuffer.append(STR_NUMBER[num.charAt(i)-48]);
tempBuffer.append(STR_UNIT2[i]);
}
return tempBuffer.toString();
}
}
运行结果如下: