douglascrockford/JSON-java — Issue #42: Bug in JSONObject when handling float values
Author: gloewy
Created: 2012-01-20 23:30:56+00:00
State: open

Hi Douglas,

Just wanted to point out a bug in your otherwise wonderful code.

Currently, putting float values into a JSONObject is using the put(String, double) method.
Unfortunately, this type of cast causes floating point precision problems.
For example, the float number 6.99 is translated to the double 6.989999771118164

To solve this issue I added the following method to the JSONObject:

/**
* Put a key/double pair in the JSONObject.
*
* @param key A key string.
* @param value A float which is the value.
* @return this.
* @throws JSONException If the key is null or if the number is invalid.
*/
public JSONObject put(String key, float value) throws JSONException {
this.put(key, Double.parseDouble(String.valueOf(value)));
return this;
}

Hopefully you could add this bug fix to your code.

Guy