方法1:
//
float i = 34.33333;
//四舍五入,只显示小数点后两位
BigDecimal b = new BigDecimal(i);
float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
mToLearnTimes.setText("已选课程:"+ f1+"小时");
// b.setScale(2, BigDecimal.ROUND_HALF_UP) 表明四舍五入,保留两位小数
方法2:
float scale = 34.236323;
DecimalFormat fnum = new DecimalFormat("##0.00");
String dd=fnum.format(scale);
方法3:
float a = 123.2334f; float b = (float)(Math.round(a*100))/100;(这里的100就是2位小数点,如果要其它位,如4位,这里两个100改成10000)
本文介绍三种在Java中将浮点数四舍五入到指定小数位的方法,包括使用BigDecimal、DecimalFormat及Math类实现,并提供具体代码实例。

1万+

被折叠的 条评论
为什么被折叠?



