Java BigDecimal 相關

Posted by Adam on August 24, 2022
### [How to print formatted BigDecimal values?](https://stackoverflow.com/questions/3395825/how-to-print-formatted-bigdecimal-values) 千位數加逗號 ```java import java.math.BigDecimal; import java.text.DecimalFormat; ``` ```java DecimalFormat df = new DecimalFormat("#,###"); System.out.println(df.format(new BigDecimal(7123456.75))); // 7,123,457 ``` ```java package poisondog.demo; import java.math.BigDecimal; /** * @author Adam Huang */ public class DemoBigDecimal { // 為需要四捨五入的數字,scale 為小數點後面要保留幾位數,return 四捨五入後的結果 public static double round(double v,int scale){ if(scale < 0){ throw new IllegalArgumentException("The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } public static void main (String [] args) throws Exception { BigDecimal bigNumber = new BigDecimal("89.1234567890123456789"); BigDecimal bigRate = new BigDecimal(1000); BigDecimal bigResult = new BigDecimal(0); // bigResult 為 bigNumBer * bigRate bigResult = bigNumber.multiply(bigRate); System.out.println(bigResult.toString()); // 89123.4567890123456789000 // 將 bigNumber 四捨五入變為 double 型態 double dData = bigNumber.doubleValue(); System.out.println(dData); // 89.12345678901235 // 宣告 data2 為 bigNumber/bigRate 並四捨五入至小數點第二位 double data2 = bigNumber.divide(bigRate, 2, BigDecimal.ROUND_HALF_UP) .doubleValue(); System.out.println(data2); // 0.09 } } ```