2014-02-11 124 views
1

使用的JSONObject發送給Web服務 當我們把雙(回合數)的零和點被刪除如何把帶小數點的DOUBLE放到JSONObject中?

CODE

double d = 123.00; 
JSONObject json = new JSONObject(); 
json.put("param", d); 
System.out.println(json.toString()); 

輸出

{"param":17} 

我可以把雙帶到JSONObject的小數點位置

回答

0

使用getDouble(String name)來讀取該值。

System.out.println(json.getDouble("param")); 

如果你看到的JSONObject

663 public String toString(int indentSpaces) throws JSONException { 
664  JSONStringer stringer = new JSONStringer(indentSpaces); 
665  writeTo(stringer); 
666  return stringer.toString(); 
667 } 
668 
669 void writeTo(JSONStringer stringer) throws JSONException { 
670  stringer.object(); 
671  for (Map.Entry<String, Object> entry : nameValuePairs.entrySet()) { 
672   stringer.key(entry.getKey()).value(entry.getValue()); 
673  } 
674  stringer.endObject(); 
675 } 

writeTo()toString()Object寫入值。所以這可能是toString()顯示雙倍意外值的原因。

+0

'getDouble()'雙截斷到小數點後一位。 –

0

娜,更好的使用這個功能,即使當u投浮到雙:

public static double roundToDouble(float d, int decimalPlace) { 
     BigDecimal bd = new BigDecimal(Float.toString(d)); 
     bd = bd.setScale(decimalPlace, BigDecimal.ROUND_HALF_UP); 
     return bd.doubleValue(); 
    } 
相關問題