(后端)Java中关于金额大小写的工具类
生活随笔
收集整理的這篇文章主要介紹了
(后端)Java中关于金额大小写的工具类
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
/**
* 金額小數轉換成中文大寫金額
*
* @author Neil Han
*
*/
private static final String UNIT[] = { "萬", "千", "佰", "拾", "億", "千", "佰", "拾", "萬", "千", "佰", "拾", "元", "角", "分" };
private static final String NUM[] = { "零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖" };
private static final double MAX_VALUE = 9999999999999.99D;
/**
* 將金額小數轉換成中文大寫金額
*
* @param money
* @return result
*/
public static String convertMoney(double money) {
if (money < 0 || money > MAX_VALUE)
return "參數非法!";
long money1 = Math.round(money * 100); // 四舍五入到分
if (money1 == 0)
return "零元整";
String strMoney = String.valueOf(money1);
int numIndex = 0; // numIndex用于選擇金額數值
int unitIndex = UNIT.length - strMoney.length(); // unitIndex用于選擇金額單位
boolean isZero = false; // 用于判斷當前為是否為零
String result = "";
for (; numIndex < strMoney.length(); numIndex++, unitIndex++) {
char num = strMoney.charAt(numIndex);
if (num == '0') {
isZero = true;
if (UNIT[unitIndex] == "億" || UNIT[unitIndex] == "萬" || UNIT[unitIndex] == "元") { // 如果當前位是億、萬、元,且數值為零
result = result + UNIT[unitIndex]; // 補單位億、萬、元
isZero = false;
}
} else {
if (isZero) {
result = result + "零";
isZero = false;
}
result = result + NUM[Integer.parseInt(String.valueOf(num))] + UNIT[unitIndex];
}
}
// 不是角分結尾就加"整"字
if (!result.endsWith("角") && !result.endsWith("分")) {
result = result + "整";
}
// 例如沒有這行代碼,數值"400000001101.2",輸出就是"肆千億萬壹千壹佰零壹元貳角"
result = result.replaceAll("億萬", "億");
return result;
}
public static void main(String[] args) {
double value = Double.parseDouble("40330701101.2");
System.out.println("您輸入的金額(小寫)為:" + value);
System.out.println("您輸入的金額(大寫)為:" + convertMoney(value));
}
總結
以上是生活随笔為你收集整理的(后端)Java中关于金额大小写的工具类的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mapbox常用表达式整理
- 下一篇: 啥是“簇”呢? 文件系统的簇答疑