From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: From: Serge Petrenko Subject: [PATCH v3 3/5] decimal: fix string formatting on construction from double Date: Tue, 2 Jul 2019 20:27:50 +0300 Message-Id: In-Reply-To: References: MIME-Version: 1.0 Content-Transfer-Encoding: 8bit To: vdavydov.dev@gmail.com Cc: tarantool-patches@freelists.org, Serge Petrenko List-ID: 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)