Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why double is converted to int in JSON string

Tags:

java

org.json

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]}

like image 821
Keerthivasan Avatar asked Feb 23 '14 08:02

Keerthivasan


3 Answers

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]}

like image 158
sakura Avatar answered Sep 20 '22 14:09

sakura


Looking at toString of net.sf.json.JSONObject it eventually calls the following method to translate the numbers to String (source code here):

public static String numberToString(Number n) {
        if (n == null) {
            throw new JSONException("Null pointer");
        }
        //testValidity(n);

        // Shave off trailing zeros and decimal point, if possible.

        String s = n.toString();
        if (s.indexOf('.') > 0 && s.indexOf('e') < 0 && s.indexOf('E') < 0) {
            while (s.endsWith("0")) {
                s = s.substring(0, s.length() - 1);
            }
            if (s.endsWith(".")) {
                s = s.substring(0, s.length() - 1);
            }
        }
        return s;
    }

It clearly tries to get rid of the trailing zeroes when it can, (s = s.substring(0, s.length() - 1) if a String is ending in zero).

System.out.println(numberToString(1.1) + " vs " + numberToString(1.0));

Gives,

1.1 vs 1
like image 21
StoopidDonut Avatar answered Sep 23 '22 14:09

StoopidDonut


All numbers are floats in Javascript. So, 1.0 and 1 are the same in JS. There is no differenciation of int, float and double.

Since JSON is going to end up as a JS object, there is no use in adding an extra '.0' since '1' represents a float as well. I guess this is done to save a few bytes in the string that is passed around.

So, you will get a float in JS, and if you parse it back to Java, you should get a double. Try it.

In the mean time, if you are interested in the way it displays on screen, you can try some string formatting to make it look like '1.0'.

like image 44
Teddy Avatar answered Sep 21 '22 14:09

Teddy