[glade] GladePropertyClass: round floating point values to epsilon



commit 1141bbd2c4676c9ea075b7bac83b0942fb56ef3e
Author: Juan Pablo Ugarte <juanpablougarte gmail com>
Date:   Tue May 22 16:57:37 2018 -0300

    GladePropertyClass: round floating point values to epsilon

 gladeui/glade-property-class.c | 34 +++++++++++++++++++++++++---------
 1 file changed, 25 insertions(+), 9 deletions(-)
---
diff --git a/gladeui/glade-property-class.c b/gladeui/glade-property-class.c
index d31d930e..b5f13c7f 100644
--- a/gladeui/glade-property-class.c
+++ b/gladeui/glade-property-class.c
@@ -448,6 +448,26 @@ glade_property_class_make_string_from_objects (GladePropertyClass *
   return string;
 }
 
+static gchar *
+glade_dtostr (double number, gdouble epsilon)
+{
+  char *str = g_malloc (G_ASCII_DTOSTR_BUF_SIZE);
+  int i;
+
+  for (i = 0; i <= 20; i++)
+    {
+      double rounded;
+
+      snprintf (str, G_ASCII_DTOSTR_BUF_SIZE, "%.*f", i, number);
+      rounded = g_ascii_strtod (str, NULL);
+
+      if (ABS (rounded - number) <= epsilon)
+        return str;
+    }
+
+  return str;
+}
+
 /**
  * glade_property_class_make_string_from_gvalue:
  * @property_class: A #GladePropertyClass
@@ -460,7 +480,7 @@ glade_property_class_make_string_from_gvalue (GladePropertyClass *
                                               property_class,
                                               const GValue * value)
 {
-  gchar *string = NULL, **strv, str[G_ASCII_DTOSTR_BUF_SIZE];
+  gchar *string = NULL, **strv;
   GObject *object;
   GdkColor *color;
   GdkRGBA *rgba;
@@ -533,15 +553,11 @@ glade_property_class_make_string_from_gvalue (GladePropertyClass *
   else if (G_IS_PARAM_SPEC_UINT64 (property_class->pspec))
     string = g_strdup_printf ("%" G_GUINT64_FORMAT, g_value_get_uint64 (value));
   else if (G_IS_PARAM_SPEC_FLOAT (property_class->pspec))
-    {
-      g_ascii_dtostr (str, sizeof (str), g_value_get_float (value));
-      string = g_strdup (str);
-    }
+    string = glade_dtostr (g_value_get_float (value),
+                           ((GParamSpecFloat *)property_class->pspec)->epsilon);
   else if (G_IS_PARAM_SPEC_DOUBLE (property_class->pspec))
-    {
-      g_ascii_dtostr (str, sizeof (str), g_value_get_double (value));
-      string = g_strdup (str);
-    }
+    string = glade_dtostr (g_value_get_double (value),
+                           ((GParamSpecDouble *)property_class->pspec)->epsilon);
   else if (G_IS_PARAM_SPEC_STRING (property_class->pspec))
     {
       string = g_value_dup_string (value);


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]