Skip to content

Commit eebc98b

Browse files
committed
Fix trailing zeros handling in rb_uint64_convert_to_BigDecimal
Fix GH-192
1 parent e864828 commit eebc98b

File tree

1 file changed

+15
-7
lines changed

1 file changed

+15
-7
lines changed

ext/bigdecimal/bigdecimal.c

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2862,21 +2862,29 @@ rb_uint64_convert_to_BigDecimal(uint64_t uval, RB_UNUSED_VAR(size_t digs), int r
28622862
}
28632863
else {
28642864
DECDIG buf[BIGDECIMAL_INT64_MAX_LENGTH] = {0,};
2865-
size_t exp = 0, ntz = 0;
2866-
for (; uval > 0; ++exp) {
2867-
DECDIG r = uval % BASE;
2868-
if (r == 0) ++ntz;
2869-
buf[BIGDECIMAL_INT64_MAX_LENGTH - exp - 1] = r;
2865+
DECDIG r = uval % BASE;
2866+
size_t len = 0, ntz = 0;
2867+
if (r == 0) {
2868+
// Count and skip trailing zeros
2869+
for (; r == 0 && uval > 0; ++ntz) {
2870+
uval /= BASE;
2871+
r = uval % BASE;
2872+
}
2873+
}
2874+
for (; uval > 0; ++len) {
2875+
// Store digits
2876+
buf[BIGDECIMAL_INT64_MAX_LENGTH - len - 1] = r;
28702877
uval /= BASE;
2878+
r = uval % BASE;
28712879
}
28722880

2873-
const size_t len = exp - ntz;
2881+
const size_t exp = len + ntz;
28742882
vp = VpAllocReal(len);
28752883
vp->MaxPrec = len;
28762884
vp->Prec = len;
28772885
vp->exponent = exp;
28782886
VpSetSign(vp, 1);
2879-
MEMCPY(vp->frac, buf + BIGDECIMAL_INT64_MAX_LENGTH - exp, DECDIG, len);
2887+
MEMCPY(vp->frac, buf + BIGDECIMAL_INT64_MAX_LENGTH - len, DECDIG, len);
28802888
}
28812889

28822890
return BigDecimal_wrap_struct(obj, vp);

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy