split code into multiple files
[calc.git] / format.c
diff --git a/format.c b/format.c
new file mode 100644 (file)
index 0000000..48cc56f
--- /dev/null
+++ b/format.c
@@ -0,0 +1,42 @@
+#include <malloc.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "format.h"
+
+/* global variables */
+
+#define DEFAULT_FORMAT "=> %.6g\n"
+char *format = NULL;
+char *minform = NULL;
+
+/* print function */
+
+void set_format (char *prompt, int precision)
+{
+    char buffer[128] = {0};
+    free_format ();
+    sprintf (buffer, "%s%%.%dg\n", prompt, precision);
+    format = strdup (buffer);
+    sprintf (buffer, "%%.%dg", precision);
+    minform = strdup (buffer);
+}
+
+void free_format ()
+{
+    if (format) {
+        free (format);
+        format = NULL;
+    }
+    if (minform) {
+        free (minform);
+        minform = NULL;
+    }
+}
+
+double print (double value)
+{
+    fprintf (stdout, format ? format : DEFAULT_FORMAT, value);
+    fflush (stdout);
+    return value;
+}