|
发表于 2020-7-27 07:45:01
|
显示全部楼层
偶也凑凑热闹:)
-----------------------------------------
public final class RMB{
private RMB(){
}
/**
* 将给定的阿拉伯数字转化为中文大写钱款
*
* @param input 给定的阿拉伯数字
* @return 中文大写钱款
*/
public static String toRMB(String input) {
if (input == null || input.equals("")) {
return "零";
}
// 判断输入是否为数字(方法不贴了,先注释了)
//if (!isNumber(input)) {
// throw new IllegalArgumentException(
// "The money input must be a number!");
//}
// 判断是否含有小数点(将给定字符串四舍五入。方法不贴了,先注释了)
//input = format(round(toDouble(input).doubleValue()));
int dotIndex = input.indexOf(".");
if (dotIndex > 0) {
if (dotIndex == input.length() - 2) {
input = input + "0";
}
else if (dotIndex == input.length() - 1) {
input = input + "00";
}
}
else {
input = input + ".00";
}
// 最多位数:15位数字
if (dotIndex > 14) {
throw new IllegalArgumentException(
"The money input is too large to convert!");
}
final String[] numbers = new String[] {"零", "壹", "贰", "叁", "肆", "伍",
"陆", "柒", "捌", "玖"};
final String[] units = new String[] {"分", "角", "元", "拾", "佰", "仟", "万",
"拾", "佰", "仟", "亿", "拾", "佰", "仟", "万"};
final String[] invalids = new String[] {"拾零元", "零[仟佰拾元角分]", "零+", "零亿",
"零万", "零元", "亿零*+万"};
final String[] valids = new String[] {"拾元", "零", "零", "亿", "万", "元",
"亿"};
// 反转给定数字
StringBuffer inputReversed = new StringBuffer(input).reverse();
inputReversed.deleteCharAt(inputReversed.indexOf("."));
// 按位转化并添加单位
StringBuffer resultBuffer = new StringBuffer();
int numberLength = inputReversed.length();
for (int index = 0; index < numberLength; index++) {
resultBuffer.append(units[index]);
resultBuffer.append(numbers[Integer.parseInt(inputReversed.charAt(index)
+ "")]);
}
// 替换非法表达方式
String result = resultBuffer.reverse().toString();
for (int i = 0; i < invalids.length; i++) {
result = result.replaceAll(invalids[i], valids[i]);
}
// 如果以零开头,则去掉零
if (result.startsWith("零")) {
result = result.substring(1, result.length());
}
// 如果以零结尾,则去掉零
if (result.endsWith("零")) {
result = result.substring(0, result.length() - 1);
}
// 如果没有角分,则添加整字
if (result.indexOf("角") < 0 && result.indexOf("分") < 0) {
result = result + "整";
}
return result;
}
public static void main(String[] args) {
String money = "100000000010.12645";
System.out.println(RMB.toRMB(money));
String moneyString = "10.01";
System.out.println(RMB.toRMB(moneyString));
}
} |
|