summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorEmmanuele Bassi <ebassi@gmail.com>2023-02-06 22:49:26 +0000
committerEmmanuele Bassi <ebassi@gmail.com>2023-02-06 22:49:26 +0000
commit5e6e76f6b91c85db158dfd960d769178b634a296 (patch)
tree5f6ceb7e1d44bfc2f5120bf0d0ae1d6cf13dba22
parentd7fb79cfd0a78478206f4bd6ae7dfc543184ed41 (diff)
parentff112e924cf648f9147c674360c9993dec53136e (diff)
downloadjson-glib-5e6e76f6b91c85db158dfd960d769178b634a296.tar.gz
Merge branch 'valid-double-exponential' into 'master'
generator: ensure valid output double exponential notation Closes #67 See merge request GNOME/json-glib!57
-rw-r--r--json-glib/json-generator.c7
-rw-r--r--json-glib/tests/generator.c28
2 files changed, 34 insertions, 1 deletions
diff --git a/json-glib/json-generator.c b/json-glib/json-generator.c
index 40e9b02..eef41a7 100644
--- a/json-glib/json-generator.c
+++ b/json-glib/json-generator.c
@@ -360,7 +360,12 @@ dump_value (GString *buffer,
g_ascii_dtostr (buf, sizeof (buf),
json_value_get_double (value)));
/* ensure doubles don't become ints */
- if (g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, ".") == NULL)
+ /* also make sure not to append .0 that results in invalid exponential notation
+ * since the numbers should be decimal, a hex 'e' or "E" can not be mistaken
+ */
+ if (g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, ".") == NULL &&
+ g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, "e") == NULL &&
+ g_strstr_len (buf, G_ASCII_DTOSTR_BUF_SIZE, "E") == NULL)
{
g_string_append (buffer, ".0");
}
diff --git a/json-glib/tests/generator.c b/json-glib/tests/generator.c
index 034de5a..db27b1a 100644
--- a/json-glib/tests/generator.c
+++ b/json-glib/tests/generator.c
@@ -350,6 +350,33 @@ test_double_stays_double (void)
json_node_free (node);
}
+static void
+test_double_valid (void)
+{
+ gchar *str;
+ JsonNode *node = json_node_new (JSON_NODE_VALUE);
+ JsonGenerator *generator = json_generator_new ();
+
+ json_node_set_double (node, 1e-8);
+ json_generator_set_root (generator, node);
+
+ str = json_generator_to_data (generator, NULL);
+ g_test_message ("%s: value: '%.2f' - string: '%s'",
+ G_STRFUNC,
+ json_node_get_double (node),
+ str);
+
+ /* should be valid double
+ * in particular; no trailing .0 for exponential notation */
+ gchar *end = NULL;
+ g_ascii_strtod(str, &end);
+ g_assert_cmpint (0, ==, *end);
+
+ g_free (str);
+ g_object_unref (generator);
+ json_node_free (node);
+}
+
static void
test_pretty (void)
@@ -439,6 +466,7 @@ main (int argc,
g_test_add_func ("/generator/nested-object", test_nested_object);
g_test_add_func ("/generator/decimal-separator", test_decimal_separator);
g_test_add_func ("/generator/double-stays-double", test_double_stays_double);
+ g_test_add_func ("/generator/double-valid", test_double_valid);
g_test_add_func ("/generator/pretty", test_pretty);
for (guint i = 0; i < G_N_ELEMENTS (string_fixtures); i++)