String 类型强制转换 float 四舍五入

               

    import java.math.BigDecimal;        
        //遍历maplist   
        List<Map<String, Object>> oldList = new ArrayList<Map<String, Object>>();
            try {
	        for (Map<String, Object> mapList : list) {
		        //将key强制转换为string
                        String mString=String.valueOf(mapList.get("subtotal"));
		        String nString=String.valueOf(mapList.get("total"));
                       //string 转换float
			float x = Float.valueOf(mString.trim()).floatValue();
			float y = Float.valueOf(nString.trim()).floatValue();
			float z = (x / y) * 100;
                        //将float转换为可以精确计算类型BigDecimal
			BigDecimal b = new BigDecimal(z);
                        //四舍五入保留小数点后两位
			float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
                        //mapList添加(key,value)
			mapList.put("perc", f1);
                        //将数据添加到列表
			oldList.add(mapList);
			}
		} catch (NumberFormatException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 

 

 

你可能感兴趣的:(String)