方法1:
float f = 34.232323;
BigDecimal b = new BigDecimal(f);
float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
// b.setScale(2, BigDecimal.ROUND_HALF_UP) 表明四舍五入,保留两位小数
方法2:
float scale = 34.236323;
DecimalFormat fnum = new DecimalFormat("##0.00");
String dd=fnum.format(scale);
System.out.println(dd);
/**
- * 四舍五入
- * @param value
- * @param scale 保留几位小数点
- * @return
- */
- public static double scaleValue(double value,short scale) {
- double result = value;
- String valueStr = String.valueOf(Math.abs(value));
- if(valueStr.contains(".")) {
- String[] temp = valueStr.split("\\.");
- String temp_0 = temp[0];
- String temp_1 = temp[1];
- if(temp_1 != null && temp_1.length() > scale) {
- BigDecimal cimal = new BigDecimal(Math.abs(value));
- result = cimal.setScale(scale,BigDecimal.ROUND_DOWN).doubleValue();
- int tempchar = Integer.parseInt(temp_1.charAt(scale)+"");
- if(tempchar >= 5) result = cimal.setScale(scale,BigDecimal.ROUND_CEILING).doubleValue();
- if(value != Math.abs(value)) result = -result;
- }
- }
- return result;
- }