最近面临着找工作,就经常上网找一些常见的面试题,这次的就是把阿拉伯金额转换为中文的金额,不多说,上代码
import java.math.RoundingMode;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.Map;
/**
* 将阿拉伯数字金额转换成中文大写数字金额的转换类
*/
public class ConvertToCNMoney {
/**
* 将阿拉伯数字金额转换成中文大写数字金额
* @param money
* @return
*/
public static String toCNMoney(double money) {
//转换成指定格式的数字
NumberFormat fmt = NumberFormat.getInstance();
fmt.setMaximumFractionDigits(2);//两位小数
fmt.setRoundingMode(RoundingMode.HALF_UP);
fmt.setGroupingUsed(false);//不要千分号
money = Double.valueOf(fmt.format(money));
Map<Integer, String> numbersMap = new HashMap<Integer, String>(10);
String[] section = {"", "萬", "億", "兆"};//拆分为四大块,精确到万亿位,即兆
// String[] positions = {"拾", "佰", "仟"};
String[] numbers = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
for (int i = 0; i < numbers.length; i++) {
numbersMap.put(i, numbers[i]);
}
String result = "";
//1.处理小数位(如果有)
if (fmt.format(money).contains(".")) {
int remainder = (int) ((money * 100) % 100);//取余
int a = remainder / 10;
if (a != 0) {
result = numbersMap.get(a) + "角";
}
int b = remainder % 10;
if (b != 0) {
if (a == 0) {
result += numbersMap.get(0) + numbersMap.get(b) + "分";//处理特殊情况,如2.05(贰圆零伍分)
} else {
result += numbersMap.get(b) + "分";
}
}
}
//2.处理整数位
long total = (long) (money * 100 / 100);//取整
if (total == 0) {
return result.equals("") ? (numbersMap.get(0) + "圆") : result;//少于1元
}
int j = 0;
String tempResult = "";
do {
//每次处理四位数
long t = (total % 10000);
String str = ConvertToCNMoney.thousandToUpperCase((int) t, numbersMap, null);
total = total / 10000;
if (total != 0 && t > 0 && t < 1000) {
str = numbersMap.get(0) + str;//如果每次处理之后还有万位且前次处理的四位取余t(0<t<1000),则前面应补零
}
tempResult = str + section[j] + tempResult;
j++;
} while (total != 0);
//3.最后别忘了金额单位
result = tempResult + "圆" + result;
System.out.print(result);
return result;
}
/**
* 处理千位以内阿拉伯数字金额
* @param number
* @param numbersMap
* @param result
* @return
*/
private static String thousandToUpperCase(int number, Map<Integer, String> numbersMap, String result) {
result = result == null ? "" : result;
if (number < 10) {
return number == 0 ? result : (result + numbersMap.get(number));//取出个位
}
if (number < 100) {
result = result + numbersMap.get(number / 10) + "拾";//取出十位
return thousandToUpperCase(number % 10, numbersMap, result);
}
if (number < 1000) {
result = result + numbersMap.get(number / 100) + "佰";//取出百位
//处理特殊情况,如201
if (0 < number % 100 && number % 100 < 10) {
result += numbersMap.get(0);//加个零
}
return thousandToUpperCase(number % 100, numbersMap, result);
}
if (number < 10000) {
result = result + numbersMap.get(number / 1000) + "仟";//取出千位
//处理特殊情况,如2001,2011
if (0 < number % 1000 && number % 1000 < 100) {
result += numbersMap.get(0);//加个零
}
return thousandToUpperCase(number % 1000, numbersMap, result);
}
return result;
}
public static void main(String args[]){
toCNMoney(12323430100982.2);
}
}
不过还是有点小问题,想知道自己敲一遍运行下就知道了