Reputation: 371
I have a json string with floating values:
{"foo":10.0,"bar":12.005}
I need to convert it using JSONObject(jsonstring)
and I need to retain the decimals, but the json array drops them if they are zero. The result looks like
{"foo":10,"bar":12.005}
I expected that i could provide additional parameters to control the data type but according to https://developer.android.com/reference/org/json/JSONObject there is no such option. I also searched google and stackoverflow but i cannot find any similar problems.
Upvotes: 1
Views: 5840
Reputation: 773
JSONObject always treats everything as Objects so they must be converted to float by parsing it.
String json = "{\"foo\":10.0}";
try{
JSONObject jo = new JSONObject(json);
float f = Float.parseFloat(jo.get("foo").toString());
System.out.println(f);
}
catch(Exception e){
// Some parsing exception occurs
}
Hope this solves the issue.
Also JSONObject supports methods for getting the items in various datatype like double, int, boolean
double d = jo.getDouble("foo");
System.out.println(d); // gave me 10.0
Similarly we have
int i = getInt("name"); // which returns an integer
boolean b = getBoolean("name"); // Automatically parses
Upvotes: 2
Reputation: 379
There's no way to get the number of digits from JSON.parse or eval. Even if IBM's decimal proposal had been adopted by the EcmaScript committee, the number is still going to be parsed to an IEEE 754 float.
Take a look a http://code.google.com/p/json-sans-eval/source/browse/trunk/src/json_sans_eval.js for a simple JSON parser that you can modify to keep precision info.
solution already provided here
How to prevent removing decimal point when parsing JSON?
Upvotes: 1
Reputation: 4442
I guess, it's not a problem of JSON array, rather language's type conversion from float to int.
Use something similar to this to format float to string String.format("%,.2f", val);
Edit
The Workflow will go as follows:
if(Math.ceil(val)==val){ //a number with no fractional points
String str = String.format("%,.2f", val);
}
else //use_the_floating_number_as_usual
Upvotes: -1
Reputation: 11
For the 10.0 it will add value as an integer in JSON, if you want it with decimal then first you need to convert it as a string and then you need to put string value in JSON.
val foo = 10.0
val bar = 12.005
val strFoo = foo.toString();
val jsonObject = JSONObject()
jsonObject.put("foo",strFoo)
jsonObject.put("bar", bar)
Upvotes: 0
Reputation: 31
This is the expected behaviour.
The DECIMAL field is converted to the JSON NUMBER data type. This type trims trailing zeros by default.
It's up to the client/receiver of the JSON to decide how many decimal places it needs to show and set the correct display format.
Upvotes: 0