在Java開發中,可能遇到金額單位的轉換,比如本系統用分作為金額的基本單位,對方系統用元作為金額的基本單位,這就需要進行單位轉換,記錄下來,方便備查。
一、分轉元
分轉元,分到元相差兩位,小數點前移2位,即除于100,long轉decimal,可使用 divide方法。
注意要使用setScale,指定小數點保留位數。
/**
* 功能:Long轉換給雙精度decimal(分轉元)
*
* @param amount
* @return
*/
public static BigDecimal transLongToDecial(Long amount) {if (null == amount) {return new BigDecimal(0);}return new BigDecimal(amount).divide(new BigDecimal("100")).setScale(2, RoundingMode.HALF_UP);
}
單元測試轉換
// 分轉元
Long amount = 1829L;
BigDecimal decialAmount = transLongToDecial(amount);
System.out.println("分轉元transLongToDecial為:" + decialAmount);
執行結果如下所示
二、元轉分
元轉分,分到元相差兩位,小數點后移2位,即乘于100,decimal轉long,可使用 multiply方法。
/*** 功能:雙精度decimal轉換Long(元轉分)* @param amount* @return*/public static Long transDecialToLong(BigDecimal amount) {if(null == amount) {return 0l;}return amount.multiply(new BigDecimal(100)).setScale(1, RoundingMode.HALF_UP).longValue();}
單元測試
// 元轉分
BigDecimal decimalAmount = new BigDecimal(18.29);
Long longAmount = transDecialToLong(decimalAmount);
System.out.println("元轉元transDecialToLong為:" + longAmount);
測試結果如下圖所示。
以上就是分和元相互轉換的工具方法,僅供參考!