如何让下面的加法中的数据都变成两位小数,而不是这么长的一段

img


如何让这段代码运行后的数据变成两位小数,答案也要求变成两位小数,那这样该怎么修改这个代码

除了楼上还可以尝试下面这两种:

// 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 方法进行保留两位小数

img

 float f = 1.12354f;
        BigDecimal bd = new BigDecimal(f);
        double f1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        System.out.print(f1);