方法一:String的format方法
double num = 1234.5678;
String str = String.format("%.2f", num);
方法二:DecimalFormat的format方法
DecimalFormat df1 = new DecimalFormat("0.00");
String str = df1.format(.1); --0.10
String str = df1.format(0.1); --0.10
String str = df1.format(0.100); --0.10
String str = df1.format(1.); --1.00
String str = df1.format(1.1); --1.10
String str = df1.format(11); --11.00
DecimalFormat df2 = new DecimalFormat("0.##");
String str = df2.format(.1); --0.1
String str = df2.format(0.1); --0.1
String str = df2.format(0.100); --0.1
String str = df2.format(1.); --1
String str = df2.format(1.1); --1.1
String str = df2.format(11); --11
DecimalFormat df3 = new DecimalFormat("#.00");
String str = df3.format(.1); --.10
String str = df3.format(0.1); --.10
String str = df3.format(0.100); --.10
String str = df3.format(1.); --1.00
String str = df3.format(1.1); --1.10
String str = df3.format(11); --11.00
DecimalFormat df4 = new DecimalFormat("#.##");
String str = df4.format(0.); --0
String str = df4.format(.1); --0.1
String str = df4.format(0.1); --0.1
String str = df4.format(0.100); --0.1
String str = df4.format(1.); --1
String str = df4.format(1.1); --1.1
String str = df4.format(11); --11
方法三:BigDecimal的setScale方法
BigDecimal bd = new BigDecimal(1234.5432);
bd = bd.setScale(2, BigDecimal.ROUND_UP); --1234.55
BigDecimal bd = new BigDecimal(1234.5678);
bd = bd.setScale(2, BigDecimal.ROUND_DOWN); --1234.56
BigDecimal bd = new BigDecimal(1234.5432);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); --1234.54
BigDecimal bd = new BigDecimal(1234.5678);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_UP); --1234.57
BigDecimal bd = new BigDecimal(1234.455);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_DOWN); --1234.45
BigDecimal bd = new BigDecimal(1234.4551);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_DOWN); --1234.46
BigDecimal bd = new BigDecimal(1234.4567);
bd = bd.setScale(2, BigDecimal.ROUND_HALF_DOWN); --1234.46
方法四:NumberFormat的setMaximumFractionDigits方法
double num = 1234.5678;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
nf.setGroupingUsed(false);
String str = nf.format(num);