public class MoneyUtils {
private static final String UNIT = "萬千佰拾億千佰拾萬千佰拾元角分";
private static final String DIGIT = "零壹貳叄肆伍陸柒捌玖";
private static final double MAX_VALUE = 9999999999999.99D;
/**
* 將double類型的元轉換成中文格式
*/
public static String change(double v) {
if (v < 0 || v > MAX_VALUE) {
return "參數非法!";
}
long l = Math.round(v * 100);
if (l == 0) {
return "零元整";
}
String strValue = l + "";
// i用來控制數
int i = 0;
// j用來控制單位
int j = UNIT.length() - strValue.length();
String rs = "";
boolean isZero = false;
for (; i < strValue.length(); i++, j++) {
char ch = strValue.charAt(i);
if (ch == '0') {
isZero = true;
if (UNIT.charAt(j) == '億' || UNIT.charAt(j) == '萬' || UNIT.charAt(j) == '元') {
rs = rs + UNIT.charAt(j);
isZero = false;
}
} else {
if (isZero) {
rs = rs + "零";
isZero = false;
}
rs = rs + DIGIT.charAt(ch - '0') + UNIT.charAt(j);
}
}
if (!rs.endsWith("分")) {
rs = rs + "整";
}
rs = rs.replaceAll("億萬", "億");
return rs;
}
/**
* 將金額分轉換成12,131.23格式的元
* 1000131 -> 10,001.31
* 100.31 -> 100.31
* 12 -> 0.12
* 100 -> 1
* 110 -> 1.1
* 10 -> 0.1
* 1 -> 0.01
* 0 -> 0
* @param amountFen 要轉換的金額 單位爲分
* @param grouping 是否以 10,001.31形式展示,否 則爲10001.31
* @param tailTrim 是否去除小數點後的0
* @return String
*/
public static String fromFenToYuan(Long amountFen,boolean grouping,boolean tailTrim){
String pattern = (amountFen == 0L) ? "0.00" : ",##0.00";
BigDecimal amountYuan = Money.toYuan(amountFen);
DecimalFormat decimalFormat = new DecimalFormat(pattern);
String formatString = decimalFormat.format(amountYuan);
if (!grouping) {
formatString = formatString.replaceAll(",","");
}
if (!tailTrim) {
return formatString;
}
if (".00".equals(formatString.substring(formatString.length() - 3))) {
return formatString.substring(0,formatString.length() - 3);
}
if ("0".equals(formatString.substring(formatString.length() - 1))) {
return formatString.substring(0,formatString.length() - 1);
}
return formatString;
}
}
Java常用Money轉換方法實現
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.