We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi. Does anybody already get this problem? I'm trying to put a float in a Json with
JSONObject item;
item=new JSONObject();
float tmp=95.7;
item.setFloat("j9T3", tmp) ;
println(item);
And for output, i got "items": [{ "alb7r": 1, "name": "", "code": "", "j9T3": 95.69999694824219 }],
??? What's up?
How to write 96.7 in my Json???
Thanks for reading and answers...
Answers
https://Processing.org/reference/float.html
@GoToLoop: must admit I was also initially surprised that setFloat() results in numerical inaccuracy...
@LiveElectonics: the cause is that internally Processing first converts the float to a double:
This is what creates the 'inaccuracy' - run this sketch and you'll see:
Like all such inaccuracies this generally isn't a major problem; since internally all your code is subject to them. Having said that if you're writing the JSON file to a server to then be served to web clients and you have a lot of floats in there I'd also be frustrated by this; as it will increase the file size unnecessarily :/
In that case:
957/10 = 95.7
Here's a wishful fix. But the evil side of
private
members are showing their ugly faces once more: X(https://Processing.org/reference/private.html
That's why for a project such as Processing, classes shouldn't use
private
but ratherprotected
.So it allows those who needs to tweak or introduce new functionalities into existing APIs. :-B
Thanks for your answers and solutions. Cheers
@goToLoop : I'm confused about your solution. How to use the put method if it's not visible ? must i tweak environement files?
also, it's said that all classes are public in processing... Sorry for these noob questions but i'm starting java and processing language
Ok the method already exist... :) just need to use it with a correct double value. Cheers
My! I didn't know setDouble() existed already. It wasn't in the reference and I didn't care to look for it straight from the source! #-o
Above was just my attempt to create setDouble() unbeknownst it was already there! X_X
I believe you've already realized that. But for precaution I'm gonna reiterate it below:
In order for setDouble() to work, either pass a
double
variable to it or suffix all literal values w/d
.Like this 1 for example:
95.7d
or957e-1d
. :-B