数字转中文
小数点前最多支持12位,总长度不超过17位
注意:当总长度达到17位(12+5)时,小数点最后一位可能会失去精度异常例如:
当输入为:1000000100.1151256—>结果为:壹拾亿零壹百点壹壹伍壹贰伍柒
为啥最后是柒我就不知道了
public static String changes(double db) {
String chinese = "零壹贰叁肆伍陆柒捌玖";
//单位
String[] unit1 = {"","","拾","百","千"};//小单位
String[] unit2 = {"","万","亿"};//大单位
//---转换后的结果---
StringBuffer resBuff = new StringBuffer();
//---数字处理---
//处理科学计数,eg:1.0E-5-->0.000010
String str = new BigDecimal(db+"").toPlainString();
//处理double类以.0结尾与因科学计数转换导致的-->0.000010以零结尾
if (str.contains(".") && str.endsWith("0")){
str = str.endsWith(".0") ? str.replace(".0","") : str.substring(0,str.length()-1);
}
String[] split = str.split("[.]");
//小数点前的
String begin = split[0];
//小数点后的
String end = null;
if(split.length == 2){
end = split[1];
}
//---小数点前处理--- begin
if("0".equals(begin)){
resBuff.append("零");
}else{
int length = begin.length();
int jw = (length-1)/4;
int yw = length-jw*4 == 0? 4 : length-jw*4;
for (char c : begin.toCharArray()) {
int i = Integer.parseInt(c + "");
char c1 = chinese.toCharArray()[i];
//多个零在一起只添加一个零
if(!(resBuff.toString().endsWith("零") && i == 0)){
resBuff.append(c1);
}
//添加单位"拾","百","千","零"后面不加单位
if(!(i == 0)){
resBuff.append(unit1[yw]);
}
if(yw == 1){
//遇到大单位以零结尾的要干掉零,eg:壹拾"零"万零壹-->引号中的零要被干掉
if(resBuff.toString().endsWith("零")){
resBuff.deleteCharAt(resBuff.length()-1);
}
//添加单位"万","亿",如果结尾直接以"万"或"亿"结尾不添加大单位:eg壹亿万-->不要在加"万"了
if(!(resBuff.toString().endsWith("亿") || resBuff.toString().endsWith("万"))){
resBuff.append(unit2[jw]);
}
jw--;
yw = 4;
}else{
yw--;
}
}
}
//---小数点后的处理---end
if(split.length == 2){
//添加"点"
resBuff.append("点");
//遍历小数点后的数字转中文
for (char c : end.toCharArray()) {
int i = Integer.parseInt(c + "");
char c1 = chinese.toCharArray()[i];
resBuff.append(c1);
}
}
return resBuff.toString();
}