Skip to content

Commit

Permalink
sprintf_s: strip leading zeros and dot on %g (not %#g)
Browse files Browse the repository at this point in the history
fixes parts of GH #68
  • Loading branch information
rurban committed Dec 26, 2024
1 parent cfcb56d commit 7119fe0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 8 deletions.
19 changes: 16 additions & 3 deletions src/str/vsnprintf_s.c
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,7 @@ static size_t safec_ftoa(out_fct_type out, const char *funcname, char *buffer,
unsigned int prec, unsigned int width,
unsigned int flags) {
char buf[PRINTF_FTOA_BUFFER_SIZE];
size_t len = 0U;
size_t len = 0U, off = 0U;
double tmp;
double diff = 0.0;
unsigned long frac;
Expand Down Expand Up @@ -525,6 +525,19 @@ static size_t safec_ftoa(out_fct_type out, const char *funcname, char *buffer,
}
}

// strip leading zeros and dots
if ((flags & FLAGS_ADAPT_EXP) && !(flags & FLAGS_HASH)) {
size_t olen = len;
while (buf[off] == '0') {
off++; len--;
if (off >= olen)
break;
}
if (buf[off] == '.' && off < olen) {
off++; len--;
}
}

if (len < PRINTF_FTOA_BUFFER_SIZE) {
if (negative) {
buf[len++] = '-';
Expand All @@ -535,7 +548,7 @@ static size_t safec_ftoa(out_fct_type out, const char *funcname, char *buffer,
}
}

return safec_out_rev(out, buffer, idx, maxlen, buf, len, width, flags);
return safec_out_rev(out, buffer, idx, maxlen, &buf[off], len, width, flags);
}

#ifdef PRINTF_SUPPORT_LONG_DOUBLE
Expand Down Expand Up @@ -743,7 +756,7 @@ static size_t safec_etoa(out_fct_type out, const char *funcname, char *buffer,
const size_t start_idx = idx;
idx = safec_ftoa(out, funcname, buffer, idx, maxlen,
negative ? -value : value, prec, fwidth,
flags & ~FLAGS_ADAPT_EXP);
flags);

// output the exponent part
if (minwidth) {
Expand Down
10 changes: 5 additions & 5 deletions tests/test_sprintf_s.c
Original file line number Diff line number Diff line change
Expand Up @@ -393,22 +393,22 @@ int test_sprintf_s(void) {
EXPSTR(str2, "0.100000")
rc = sprintf_s(str2, LEN, "%g", 0.1);
NOERRNULL()
EXPSTR(str2, "0.1") // FIXME 0.100000 trailing-zeros not stripped
EXPSTR(str2, "0.1")
rc = sprintf_s(str2, LEN, "%#g", 0.1); // alternate form
NOERRNULL()
EXPSTR(str2, "0.100000")
rc = sprintf_s(str2, LEN, "%G", 0.1);
NOERRNULL()
EXPSTR(str2, "0.1") // FIXME 0.100000 trailing-zeros not stripped
EXPSTR(str2, "0.1")
rc = sprintf_s(str2, LEN, "%g", 0.1f);
NOERRNULL()
EXPSTR(str2, "0.1") // FIXME 0.100000 trailing-zeros not stripped
EXPSTR(str2, "0.1")
rc = sprintf_s(str2, LEN, "%g", 1.0);
NOERRNULL()
EXPSTR(str2, "1") // FIXME 0.100000 trailing-zeros and dot not stripped
EXPSTR(str2, "1")
rc = sprintf_s(str2, LEN, "%lg", 0.1);
NOERRNULL()
EXPSTR(str2, "0.1") // FIXME 0.100000 trailing-zeros not stripped
EXPSTR(str2, "0.1")
rc = sprintf_s(str2, LEN, "%a", 0.1f);
NOERRNULL()
EXPSTR(str2, "0x1.99999ap-4")
Expand Down

0 comments on commit 7119fe0

Please sign in to comment.