Why double is converted to int in JSON string

独自空忆成欢 提交于 2019-12-01 16:05:25

问题


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


回答1:


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




回答2:


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'.




回答3:


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


来源:https://stackoverflow.com/questions/21965828/why-double-is-converted-to-int-in-json-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!