Simplify float serialization round-trip fix

This commit is contained in:
Steve 2026-06-17 01:46:36 -04:00
parent 794936abda
commit 803e82e2f9

View File

@ -7,8 +7,6 @@
#include <stdarg.h> #include <stdarg.h>
#include <assert.h> #include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h> #include <ctype.h>
void c11_sbuf__ctor(c11_sbuf* self) { void c11_sbuf__ctor(c11_sbuf* self) {
@ -55,24 +53,18 @@ void c11_sbuf__write_f64(c11_sbuf* self, double val, int precision) {
char b[32]; char b[32];
int size; int size;
if(precision < 0) { if(precision < 0) {
// Pick the shortest decimal width that round-trips to the same binary double. size = snprintf(b, sizeof(b), "%.17g", val);
for(int prec = 15; prec <= 17; prec++) { c11_sbuf__write_cstr(self, b);
size = snprintf(b, sizeof(b), "%.*g", prec, val);
double parsed = strtod(b, NULL);
if(memcmp(&parsed, &val, sizeof(double)) == 0) break;
}
bool all_is_digit = true; bool all_is_digit = true;
for(int i = 1; i < size; i++) { for(int i = 1; i < size; i++) {
if(!isdigit(b[i])) { if(!isdigit((unsigned char)b[i])) {
all_is_digit = false; all_is_digit = false;
break; break;
} }
} }
c11_sbuf__write_cstr(self, b);
if(all_is_digit) c11_sbuf__write_cstr(self, ".0"); if(all_is_digit) c11_sbuf__write_cstr(self, ".0");
} else { } else {
int prec = precision; size = snprintf(b, sizeof(b), "%.*f", precision, val);
size = snprintf(b, sizeof(b), "%.*f", prec, val);
c11_sbuf__write_cstr(self, b); c11_sbuf__write_cstr(self, b);
} }
} }