除了楼上还可以尝试下面这两种:
// 1.
Random random = new Random();
float f1 = (float) Math.round(random.nextFloat() * 100) / 100;
float f2 = (float) Math.round(random.nextFloat() * 100) / 100;
System.out.println(f1 + " + " + f2);
// 2.
DecimalFormat decimalFormat = new DecimalFormat("0.00");
String s1 = decimalFormat.format(random.nextFloat());
String s2 = decimalFormat.format(random.nextFloat());
System.out.println(s1 + " + " + s2);
// 3.BigDecimal
输出:
0.5 + 0.23
0.24 + 0.18
可以使用BigDecimal 方法进行保留两位小数
float f = 1.12354f;
BigDecimal bd = new BigDecimal(f);
double f1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.print(f1);