今天在网络上找JAVA版本的数字转人民币大写,找了几个版本,下载使用后都不怎么理想,或多或少存在点问题,另外一个原因就是出现了更大的金额兆(万亿),最后在前辈的基础上自己动手写了一个版本。
网络上找的版本在处理小数点前面部分基本都是一个整体考虑,这次自己写的版本则采用4位一个分割的方式处理,测试后的结果和WPS的EXCEL进行了对比,测试案例中都保持了一致,草稿版本,有问题欢迎指正。
测试过程中也发现了WPS的EXCEL对数字转人民币大写的最高限制,见图片黄色部分:
代码如下:
-
import java.math.BigDecimal;
-
import java.text.DecimalFormat;
-
-
public class ToChinseMoney {
-
-
private static String[] unit = {"", "万", "亿", "兆", "京"};
-
private static String[] beforeScale = {"仟", "佰", "拾", ""};
-
private static String[] numArray = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"};
-
private static String[] afterScale = {"角", "分"};
-
-
public static String toUpperCaseZhCn(BigDecimal value) {
-
StringBuffer buf = new StringBuffer();
-
if (value.compareTo(new BigDecimal("0")) < 0)
-
buf.append("负");
-
value = value.abs();
-
String c[] = value.toString().split("\\.");//分割出来,.前面对应角分
-
splitByFour(c[0], buf);
-
-
if (c.length > 1 && (c[1].toCharArray()[0] - 48 != 0 || c[1].toCharArray()[1] - 48 != 0)) {
-
char[] decimal = c[1].toCharArray();
-
if (decimal[0] - 48 == 0)
-
buf.append(numArray[decimal[0] - 48]);
-
else
-
buf.append(numArray[decimal[0] - 48]).append(afterScale[0]);
-
if (decimal.length > 1 && decimal[1] - 48 != 0)
-
buf.append(numArray[decimal[1] - 48]).append(afterScale[1]);
-
}
-
-
return buf.toString();
-
}
-
-
public static void splitByFour(String strIntpart, StringBuffer buf) {
-
if(new BigDecimal("0").equals( new BigDecimal(strIntpart)))
-
{
-
buf.append("零");
-
return;
-
}
-
-
DecimalFormat df4 = new DecimalFormat("####,####,####,####,####");
-
String formatMount = df4.format(new BigDecimal(strIntpart));
-
String[] splitList = formatMount.split(",");
-
if (splitList.length > 5) {
-
System.out.println("金额超限!");
-
// throw new Exception("金额超限!");
-
}
-
for (int n = 0; n < splitList.length; n++) {
-
String onePart = splitList[n];
-
if (Integer.parseInt(onePart) != 0){
-
RecursionChangeTo(onePart, buf, false);
-
buf.append(unit[splitList.length - 1 - n]);
-
}
-
}
-
-
}
-
-
public static void RecursionChangeTo(String strIntpart, StringBuffer buf, boolean preIsZero) {
-
BigDecimal Intpart = new BigDecimal(strIntpart);
-
boolean iszero = false;
-
-
String topone = "";
-
if (strIntpart.length() > 1)
-
topone = strIntpart.substring(0, 1);
-
else
-
topone = strIntpart;
-
int inttopone = Integer.parseInt(topone);
-
-
if (inttopone != 0) {
-
if (preIsZero)//前面是0 ,这里不是0
-
buf.append("零");
-
//金额部分
-
buf.append(numArray[inttopone]);
-
//单位部分
-
buf.append(beforeScale[beforeScale.length - strIntpart.length()]);
-
} else
-
iszero = true;
-
-
if (strIntpart.length() > 1) {
-
String nextString = strIntpart.substring(1, strIntpart.length());
-
if (inttopone != 0)
-
RecursionChangeTo(nextString, buf, false);
-
else
-
RecursionChangeTo(nextString, buf, true);
-
}
-
}
-
-
-
-
}
阅读(292) | 评论(0) | 转发(0) |