From b045a37391a2b2e2d674cc6967b16e57538dd786 Mon Sep 17 00:00:00 2001 From: Ryan Flynn Date: Sat, 3 Nov 2012 22:20:54 -0700 Subject: [PATCH] issue #31: encode floating point numbers with less precision if possible. fails a few etap tests, though I believe it's due to the specific values expected --- c_src/encoder.c | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/c_src/encoder.c b/c_src/encoder.c index ce71c1b..00a9dba 100644 --- a/c_src/encoder.c +++ b/c_src/encoder.c @@ -4,6 +4,7 @@ #include #include #include +#include #include "erl_nif.h" #include "jiffy.h" @@ -401,7 +402,12 @@ enc_double(Encoder* e, double val) start = &(e->p[e->i]); - sprintf(start, "%0.20g", val); + // try to encode doubles using the fewest digits possible... + if (snprintf(start, 32, "%.*g", DBL_DIG, val) > FLT_DIG) + { + // ...fall back to full expansion to be safe + snprintf(start, 32, "%.*g", LDBL_DIG, val); + } len = strlen(start); // Check if we have a decimal point