-
Notifications
You must be signed in to change notification settings - Fork 2.6k
Description
I find the floating-point number loses its decimal point after it is converted to a string, when the number doesn't have a fractional part. And it might cause exception when the string is parsed back to an JSON object in another context (C++).
I have code like the below.
JSONObject o = new JSONObject();
double d = 1960;
int i = 1980;
o.put("DOUBLE", d);
o.put("INT", i);
String text = o.toString(4);
System.out.println(text);
Variable d is a double. So it is expected to have a decimal point so that I can parse it into a floating-point number. But the output is the below, which omits the decimal point.
{
"DOUBLE": 1960,
"INT": 1980
}
I parse it with another JSON library in C++ then. It throws an exception when I get the 'DOUBLE' as double, as it should be. The field is parsed as an integer in the end.
I track down to the code between line 997 and 1001 in JSONObject.java.
public static String numberToString(Number number) throws JSONException {
if (number == null) {
throw new JSONException("Null pointer");
}
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
if (string.indexOf('.') > 0 && string.indexOf('e') < 0
&& string.indexOf('E') < 0) {
while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
I could fix the problem, but I still have two questions:
1. Why does it shave off trailing zeros and decimal point ?
2. Is it a bug or you make it with intention ?