Skip to content

Commit

Permalink
Use correct IEEE 754 float decimal precision
Browse files Browse the repository at this point in the history
In order to be able to preserve float values correctly in the JSON we need to serialize them with the correct precision. FLT_DECIMAL_DIG (introduced in C11) is "the decimal precision required to serialize/deserialize a floating point value".
  • Loading branch information
LxLasso committed Sep 21, 2020
1 parent 5aad1b5 commit 876df29
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions cgltf_write.h
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,13 @@ typedef struct {

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

#ifdef FLT_DECIMAL_DIG
// FLT_DECIMAL_DIG is C11
#define CGLTF_DECIMAL_DIG (FLT_DECIMAL_DIG)
#else
#define CGLTF_DECIMAL_DIG 9
#endif

#define CGLTF_SPRINTF(...) { \
context->tmp = snprintf ( context->cursor, context->remaining, __VA_ARGS__ ); \
context->chars_written += context->tmp; \
Expand Down Expand Up @@ -224,7 +231,7 @@ static void cgltf_write_floatprop(cgltf_write_context* context, const char* labe
{
cgltf_write_indent(context);
CGLTF_SPRINTF("\"%s\": ", label);
CGLTF_SPRINTF("%g", val);
CGLTF_SPRINTF("%.*g", CGLTF_DECIMAL_DIG, val);
context->needs_comma = 1;

if (context->cursor)
Expand Down Expand Up @@ -256,11 +263,11 @@ static void cgltf_write_floatarrayprop(cgltf_write_context* context, const char*
{
if (i != 0)
{
CGLTF_SPRINTF(", %g", vals[i]);
CGLTF_SPRINTF(", %.*g", CGLTF_DECIMAL_DIG, vals[i]);
}
else
{
CGLTF_SPRINTF("%g", vals[i]);
CGLTF_SPRINTF("%.*g", CGLTF_DECIMAL_DIG, vals[i]);
}
}
CGLTF_SPRINTF("]");
Expand Down

0 comments on commit 876df29

Please sign in to comment.