refactor: in tr_truncd(), use DBL_DIG in printf() (#1186)

Previously it was calculated from `log10(1.0 / DBL_EPISILON) - 1`;
however, there's no need to calculate it out when there's an ANSI
standard that already spells it out consisely.
This commit is contained in:
Charles Kerr 2020-05-01 22:11:45 -05:00 committed by GitHub
parent 2123adf8e5
commit 87c9287b6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 6 additions and 4 deletions

View File

@ -414,6 +414,9 @@ static int test_truncd(void)
tr_snprintf(buf, sizeof(buf), "%.0f", tr_truncd(3.3333, 0));
check_str(buf, ==, "3");
tr_snprintf(buf, sizeof(buf), "%.0f", tr_truncd(3.9999, 0));
check_str(buf, ==, "3");
#if !(defined(_MSC_VER) || (defined(__MINGW32__) && defined(__MSVCRT__)))
/* FIXME: MSCVRT behaves differently in case of nan */
tr_snprintf(buf, sizeof(buf), "%.2f", tr_truncd(nan, 2));

View File

@ -17,9 +17,9 @@
#include <ctype.h> /* isdigit(), tolower() */
#include <errno.h>
#include <float.h> /* DBL_EPSILON */
#include <float.h> /* DBL_DIG */
#include <locale.h> /* localeconv() */
#include <math.h> /* pow(), fabs(), floor() */
#include <math.h> /* fabs(), floor() */
#include <stdio.h>
#include <stdlib.h> /* getenv() */
#include <string.h> /* strerror(), memset(), memmem() */
@ -1625,8 +1625,7 @@ double tr_truncd(double x, int precision)
{
char* pt;
char buf[128];
int const max_precision = (int)log10(1.0 / DBL_EPSILON) - 1;
tr_snprintf(buf, sizeof(buf), "%.*f", max_precision, x);
tr_snprintf(buf, sizeof(buf), "%.*f", DBL_DIG, x);
if ((pt = strstr(buf, localeconv()->decimal_point)) != NULL)
{