Java中double型別的資料精確到小數點後兩位
阿新 • • 發佈:2019-01-23
轉自:http://blog.sina.com.cn/s/blog_69bd73800100yaej.html
多餘位四捨五入,四種方法
一:
double f = 111231.5585; BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
二:
new java.text.DecimalFormat("#.00").format(3.1415926)
三:
double d = 3.1415926;String result = String .format("%.2f");
四:
NumberFormat ddf1=NumberFormat.getNumberInstance() ;
void setMaximumFractionDigits(int digits)
不過第一個方法有點懷具,double f = 5; 格式化後的結果是5.0而不是5.00;
第二個方法也有不足,new java.text.DecimalFormat("#.00").format(0);的結果是.00而不是0.00;
其它的方法沒有測試。