Java中double類型的數據精確到小數點后兩位
多余位四舍五入,四種方法
一:
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;
其它的方法沒有測試。
其他
2.Math.round(d*100)/100; 3.java.math.BigDecimal(d).setScale(2,BigDecimal.ROUND_HALF_UP);
4.(new java.text.DecimalFormat("#.##")).format(d);
1.利用Math.round()的方法: 兩個int型的數相除,結果保留小數點后兩位: int a=1188;int b=93;double c;c=(double)(Math.round(a/b)/100.0);//這樣為保持2位 打印結果:c=0.12 c=new Double(Math.round(a/b)/1000.0);//這樣為保持3位 打印結果:c=0.012
來自 http://blog.sina.com.cn/s/blog_69bd73800100yaej.html