java保留两位小数4种方法
4种方法,都是四舍五入,例:
1.import java.math.BigDecimal;
2.import java.text.DecimalFormat;
3.import java.text.NumberFormat;
4.5.public class format {
6.??? double f = 111231.5585;
7.??? public void m1() {
8.??????? BigDecimal bg = new BigDecimal(f);
9.??????? double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
10.??????? System.out.println(f1);
11.??? }
12.??? /**
13.???? * DecimalFormat转换最简便
14.???? */15.??? public void m2() {
16.??????? DecimalFormat df = new DecimalFormat("#.00");
17.??????? System.out.println(df.format(f));
18.??? }
19.??? /**
20.???? * String.format打印最简便
21.???? */22.??? public void m3() {
23.??????? System.out.println(String.format("%.2f", f));
24.??? }
25.??? public void m4() {
26.??????? NumberFormat nf = NumberFormat.getNumberInstance();
27.??????? nf.setMaximumFractionDigits(2);
28.??????? System.out.println(nf.format(f));
29.??? }
30.??? public static void main(String[] args) {
31.??????? format f = new format();
32.??????? f.m1();
33.??????? f.m2();
34.??????? f.m3();
35.??????? f.m4();
36.??? }
37.}
结果:
111231.56
111231.56
111231.56
111,231.56
?
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ming1683/archive/2008/10/31/3195058.aspx