json_real(float or double value)

627 views
Skip to first unread message

SJwith

unread,
Apr 10, 2014, 1:40:28 AM4/10/14
to jansso...@googlegroups.com
json_real(25.89)
-> 25.8899999999999999

json_real((double)25.89)
-> 25.8899999999999999

json_real((float)25.89)
-> 25.8899999999999999


json_t* rtmp = json_real(0.0);
json_real_set(rtmp, 25.89);

->25.890000000000001


can I express float or double value exactly (like 25.89)
plz help;
do I use wrong way?;;

json_real(0.1)
-> 0.09999999999999999

json_real(0.2)
->0.019999999999999999

json_real(55.98)
->55.9799999999999999

Petri Lehtinen

unread,
Apr 10, 2014, 5:34:34 AM4/10/14
to jansso...@googlegroups.com
You do nothing wrong. What you're seeing is a "feature" of IEEE 754
floating points.

There's no exact binary representation for the decimal numbers 25.89,
0.1, 0.2 or 55.98, and many others. So when converted to double and
back to decimal again with precision 17 you get a different end
result.

Precision 17 is required, because otherwise some numbers would lose
precision. For example:

printf("%.17g", 1.0000000000000002)
-> 1.0000000000000002

(this is what e.g. json_dumps uses internally)

But:

printf("%.16g", 1.0000000000000002)
-> 1.0

So if Jansson used less precision, you would get a rounded result.

Petri

Basile Starynkevitch

unread,
Apr 10, 2014, 3:26:34 AM4/10/14
to jansso...@googlegroups.com
On Wed, Apr 09, 2014 at 10:40:28PM -0700, SJwith wrote:
> json_real(25.89)
> -> 25.8899999999999999

> can I express float or double value exactly (like 25.89)
> plz help;


The short answer is no, and your question is not JSON or jansson specific....

Read
http://floating-point-gui.de/
http://en.wikipedia.org/wiki/Floating_point
http://en.wikipedia.org/wiki/IEEE_floating_point

Cheers.
--
Basile STARYNKEVITCH http://starynkevitch.net/Basile/
email: basile<at>starynkevitch<dot>net mobile: +33 6 8501 2359
8, rue de la Faiencerie, 92340 Bourg La Reine, France
*** opinions {are only mines, sont seulement les miennes} ***
Message has been deleted

SJwith

unread,
Apr 13, 2014, 9:54:12 PM4/13/14
to jansso...@googlegroups.com


2014년 4월 10일 목요일 오후 4시 26분 34초 UTC+9, Basile Starynkevitch 님의 말:
thanks for interest my ask
i'm newbie programmer and feel i need much study;
I could find in strconv.c precision expression - "%.17g" (with Petri's advice, thnkyou so much;)
thanks for your advice and reference

I'll meet my team in parse part 
thanks for helps
Reply all
Reply to author
Forward
0 new messages