Teeranai.P
Teeranai.P

Reputation: 119

How to put DOUBLE with decimal place to JSONObject?

using JSONObject to send to web service when we put double (round number) the zero and the point gets removed

CODE

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

Output

{"param":17}

Can I put double with decimal place to JSONObject

Upvotes: 3

Views: 4859

Answers (2)

M. Usman Khan
M. Usman Khan

Reputation: 4448

Na, better use this function, even when u cast float to double:

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();
    }

Upvotes: 0

Pankaj Kumar
Pankaj Kumar

Reputation: 83008

Use getDouble(String name) to read that value.

Like

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

If you see toString() of 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() writes values as Object. So it might be the reason of toString() showing unexpected value for double.

Upvotes: 1

Related Questions