[PATCH v3 3/5] decimal: fix string formatting on construction from double

Serge Petrenko sergepetrenko at tarantool.org
Tue Jul 2 20:27:50 MSK 2019


Use printf "%g" option instead of "%f" to trim traling zeros in such
cases:
decimal_from_double(1) -> '1.000000000000000' -> decimal_from_string()
Now it should be
decimal_from_double(1) -> '1' ->decimal_from_string()

Follow-up 6d62c6c19ed418932ead1bba44fcd7cd84c78a19
---
 src/lib/core/decimal.c | 10 +++++++++-
 test/unit/decimal.c    |  3 ++-
 2 files changed, 11 insertions(+), 2 deletions(-)

diff --git a/src/lib/core/decimal.c b/src/lib/core/decimal.c
index 91ee3f307..1b4f44362 100644
--- a/src/lib/core/decimal.c
+++ b/src/lib/core/decimal.c
@@ -121,7 +121,15 @@ decimal_from_double(decimal_t *dec, double d)
 	char buf[DECIMAL_MAX_DIGITS + 3];
 	if (isinf(d) || isnan(d))
 		return NULL;
-	snprintf(buf, sizeof(buf), "%.*f", DBL_DIG, d);
+	/*
+	 * DBL_DIG is 15, it is the guaranteed amount of
+	 * correct significant decimal digits in a double
+	 * value.  There is no point in using higher precision,
+	 * since every non-representable number has a long
+	 * tail of erroneous digits:
+	 * `23.42` -> `23.420000000000001705302565824240446091`
+	 */
+	snprintf(buf, sizeof(buf), "%.*g", DBL_DIG, d);
 	return decimal_from_string(dec, buf);
 }
 
diff --git a/test/unit/decimal.c b/test/unit/decimal.c
index ae806a106..b587e1f14 100644
--- a/test/unit/decimal.c
+++ b/test/unit/decimal.c
@@ -27,7 +27,8 @@
 	\
 	is(decimal_div(&t, &u, &v), &t, "decimal("#a") / decimal("#b")");\
 	is(decimal_from_double(&w, (double)((a)) / (b)), &w, "decimal(("#a") / ("#b"))");\
-	is(decimal_round(&t, DBL_DIG), &t, "decimal_round(("#a")/("#b"), %d)", DBL_DIG);\
+	is(decimal_round(&t, DBL_DIG - decimal_precision(&t) + decimal_scale(&t)), &t,\
+	   "decimal_round(("#a")/("#b"), %d)", DBL_DIG);\
 	is(decimal_compare(&t, &w), 0, "decimal("#a") / decimal("#b") == ("#a") / ("#b")");\
 })
 
-- 
2.20.1 (Apple Git-117)




More information about the Tarantool-patches mailing list