今天開發碰到個需求就是保證回顯到頁面的數據保留兩位小數,實際我們的數據是八位小數
可以明顯的看到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"); }
這段代碼其實也可以不要的,我是因為前端大兄弟因為我已經改了一次代碼,不好意思再麻煩人家就寫了這么段代碼。