Prince Authenticode
Prince Authenticode

Reputation: 3

How to put DOUBLE with decimal place to JSONObject? ex:- 34.0

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

    JSONObject ctx = new JSONObject();
    try {
        ctx.put("csrf", vfModel.getCsrf());
        ctx.put("vid", vid);
        ctx.put("ns", "");
        ctx.putOpt("ver",BigDecimal.valueOf(34.0));
        
       } catch (JSONException e) {
        e.printStackTrace();
        Log.e(TAG, "JSONException null generateToken: " + e.getMessage());
    }

Output

{"csrf":"VmpFPSxNakF5TVMwd01pMHhNbFF4TXpveE16b3pNaTQ1TkRSYSwwVUVJT3kycmh6SGRYY01EZ1BWR1I3LE0yTmtaV1V6","vid":"06690000005lUNp","ns":"","ver":34}
     

Upvotes: 0

Views: 955

Answers (1)

Axel
Axel

Reputation: 14169

There’s too much to worry about in that code.

  1. Of course the point gets removed. As a double, 34 and 34.0 are indistinguishable.
  2. Never use the Bigdecimal(double) constructor unless you know exactly what you are doing. The BigDecimal can only ever be as good as the argument you pass in. But precision is lost when converting the number you typed into a double to pass as argument to the constructor. Use BigDecimal(String) instead.
  3. ver looks like it should be a version number. If it is, BigDecimal is not the type you should be using unless you are 100% sure that you can live with the restrictions it brings (like not being able to call a release "34.0.1").

If you understand everything I write above and still want to use BigDecimal, use new BigDecimal("34.0").

Upvotes: 2

Related Questions