Why double is converted to int in JSON string

Keerthivasan picture Keerthivasan · Feb 23, 2014 · Viewed 28.3k times · Source

I just coded to put an array of double values in the JsonObject. But, all my double values are converted to int values, when i print it. can someone help me understand what is happening behind? Please let me know the best way to put primitive arrays in JsonObject

public class JsonPrimitiveArrays {        
    public static void main(String[] args) {
        JSONObject jsonObject = new JSONObject();
        double[] d = new double[]{1.0,2.0,3.0};
        jsonObject.put("doubles",d);
        System.out.println(jsonObject);            
    }        
}

Output:

{"doubles":[1,2,3]}

Answer

sakura picture sakura · Feb 23, 2014

Its in real not getting converted into int. Only thing happening is as JS Object its not showing .0 which is not relevant.

In your sample program, change some of the value from double[] d = new double[]{1.0,2.0,3.0} to

double[] d = new double[]{1.0,2.1,3.1} and run the program.

You will observer its in real not converting into int. The output you will get is {"doubles":[1,2.1,3.1]}