Skip to content

Commit dc6b5f1

Browse files
authored
Merge pull request #126 from LxLasso/write_float_roundtrip
Ensure float roundtrip precision in write
2 parents 468ad38 + 876df29 commit dc6b5f1

File tree

1 file changed

+10
-3
lines changed

1 file changed

+10
-3
lines changed

cgltf_write.h

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,13 @@ typedef struct {
9696

9797
#define CGLTF_MIN(a, b) (a < b ? a : b)
9898

99+
#ifdef FLT_DECIMAL_DIG
100+
// FLT_DECIMAL_DIG is C11
101+
#define CGLTF_DECIMAL_DIG (FLT_DECIMAL_DIG)
102+
#else
103+
#define CGLTF_DECIMAL_DIG 9
104+
#endif
105+
99106
#define CGLTF_SPRINTF(...) { \
100107
context->tmp = snprintf ( context->cursor, context->remaining, __VA_ARGS__ ); \
101108
context->chars_written += context->tmp; \
@@ -224,7 +231,7 @@ static void cgltf_write_floatprop(cgltf_write_context* context, const char* labe
224231
{
225232
cgltf_write_indent(context);
226233
CGLTF_SPRINTF("\"%s\": ", label);
227-
CGLTF_SPRINTF("%g", val);
234+
CGLTF_SPRINTF("%.*g", CGLTF_DECIMAL_DIG, val);
228235
context->needs_comma = 1;
229236

230237
if (context->cursor)
@@ -256,11 +263,11 @@ static void cgltf_write_floatarrayprop(cgltf_write_context* context, const char*
256263
{
257264
if (i != 0)
258265
{
259-
CGLTF_SPRINTF(", %g", vals[i]);
266+
CGLTF_SPRINTF(", %.*g", CGLTF_DECIMAL_DIG, vals[i]);
260267
}
261268
else
262269
{
263-
CGLTF_SPRINTF("%g", vals[i]);
270+
CGLTF_SPRINTF("%.*g", CGLTF_DECIMAL_DIG, vals[i]);
264271
}
265272
}
266273
CGLTF_SPRINTF("]");

0 commit comments

Comments
 (0)