今天开发碰到个需求就是保证回显到页面的数据保留两位小数,实际我们的数据是八位小数
可以明显的看到Bigdecimal是八位,虽说Long类型不用保留两位(强迫症),但是我还是想保留
1.Long类型
String.format("%.2f",参数) 。第二个参数是double数据类型,String,int,Long 类型是不行的,float可以
2.返回的数据类型是Bigdecimal
2.1 方法一
java.text.DecimalFormat df =new java.text.DecimalFormat("#.00"); //保留整数,并且取两位小数
theNewResult.put("num1",df.format( theResut.get("num1")));
java.text.DecimalFormat的具体用法
https://www.cnblogs.com/hq233/p/6539107.html
2.2 方法二
theNewResult.put("num1", String .format("%.2f", ((BigDecimal)theResut.get("num1")).doubleValue() ));
//返回的num1是BigDecimal类型
API简单,代码也简洁了但是可读性很差,
3.double
double就很简单了使用 String.format("%.2f",参数) 参数位置是double类型,注意一点是返回值类型是String
-------------------------------------------------------
【2019-10-16】
之前代码
List<Map<String,Object>> theResults = this.ep22SoilMetallGoalService.queryMapBySQL(RouteInfor.buildRouteInfoForMstrNode(), theSql, theHelper.Params(), "", theOrderSql, theEsHelper.params(), null); Map<String,Double> newItem = new HashMap<>(); java.text.DecimalFormat df = new DecimalFormat("#.00"); for (Map<String,Object> item : theResults){ //所有数据都保留了以为小数 String valueTemp = df.format(item.get("EP22_VALUE")); Double value = Double.parseDouble(valueTemp); newItem.put(String.valueOf(item.get("EP22_NAME")) , value); } dataMap = new ArrayList<Map.Entry<String,Double>>(newItem.entrySet()); Collections.sort(dataMap,new Comparator<Map.Entry<String,Double>>(){ @Override public int compare(Map.Entry<String, Double> o1, Map.Entry<String, Double> o2) { return o2.getValue().compareTo(o1.getValue()); } }); dataMap = dataMap;
上面的代码写完了我还得意洋洋的。组长看完代码就说:你把代码写死了!
哎o(︶︿︶)o 唉 ,难受!
组长:人家是三维输数据,你写成了二维,这样再加个字段你怎么解决?
说啥来啥,甲方改需求让值相同的排序用序列号也相同,Map里面要加个key。安装上面的路子要写很多代码,下面代码是改之后的。
for(Map<String,Object> temp : theResults){ temp.put((String)temp.get("name"),temp.get("value")); temp.remove("name"); temp.remove("value"); }
这段代码其实也可以不要的,我是因为前端大兄弟因为我已经改了一次代码,不好意思再麻烦人家就写了这么段代码。