BigDecimal decimal = new BigDecimal(0.005);
BigDecimal decimal2 = new BigDecimal(0.015);
DecimalFormat df =new DecimalFormat("0.##");
df.setRoundingMode(RoundingMode.HALF_UP);
System.out.println(df.format(decimal.doubleValue()));
System.out.println(df.format(decimal2.doubleValue()));輸出的答案都是0.01 為什么,我希望第二個輸入的是0.02
4 回答
嗶嗶one
TA貢獻1854條經驗 獲得超8個贊
如果需要保證精度,最好是不要使用BigDecimal的double參數的構造函數,因為存在損失double參數精度的可能,最好是使用BigDecimal的String參數的構造函數。最好是杜絕使用BigDecimal的double參數的構造函數。
搖曳的薔薇
TA貢獻1793條經驗 獲得超6個贊
new BigDecimal最好用string,你直接寫數字的話,結果不是你想要的,
這樣:BigDecimal decimal2 = new BigDecimal("0.015");
如果需要保證精度,最好是不要使用BigDecimal的double參數的構造函數,因為存在損失double參數精度的可能,最好是使用BigDecimal的String參數的構造函數。最好是杜絕使用BigDecimal的double參數的構造函數
添加回答
舉報
0/150
提交
取消

