float f = 2.546546546454564f;
BigDecimal b = new BigDecimal(influCount);
f = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
System.out.println(f);
输出结果为2.55。
BigDecmal类setScale()方法说明参考下图:
参数定义
ROUND_CEILING
Rounding mode to round towards positive infinity.
向正无穷方向舍入
ROUND_DOWN
Rounding mode to round towards zero.
向零方向舍入
ROUND_FLOOR
Rounding mode to round towards negative infinity.
向负无穷方向舍入
ROUND_HALF_DOWN
Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
向(距离)最近的一边舍入,除非两边(的距离)是相等,如果是这样,向下舍入, 例如1.55 保留一位小数结果为1.5