humanize a number for the scale - ploot - simple plotting tools
(HTM) git clone git://bitreich.org/ploot git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65d7roiv6bfj7d652fid.onion/ploot
(DIR) Log
(DIR) Files
(DIR) Refs
(DIR) Tags
(DIR) README
(DIR) LICENSE
---
(DIR) commit 04a8bcf172e92e0f70bc889b5181bc3cbdb8f381
(HTM) Author: Josuah Demangeon <mail@josuah.net>
Date: Fri, 2 Feb 2018 02:16:15 +0100
humanize a number for the scale
Diffstat:
A .gitignore | 2 ++
A Makefile | 4 ++++
A plot | 0
A plot.c | 37 +++++++++++++++++++++++++++++++
4 files changed, 43 insertions(+), 0 deletions(-)
---
(DIR) diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,2 @@
+*.o
+./plot
(DIR) diff --git a/Makefile b/Makefile
@@ -0,0 +1,4 @@
+CFLAGS = -Wall -Wextra -Werror -std=c89 -pedantic
+
+all: plot.o
+ ${CC} -o plot plot.o
(DIR) diff --git a/plot b/plot
Binary files differ.
(DIR) diff --git a/plot.c b/plot.c
@@ -0,0 +1,37 @@
+#include <stdio.h>
+
+#define ABS(x) ((x) < 0 ? -(x) : (x))
+
+/*
+ * Set `str' to a human-readable form of `num' with always a width of 8
+ * (including '\0' terminator).
+ */
+void
+humanize(double num, char *str, size_t len)
+{
+ int exp;
+ char *label = " kMGTE", fmt[] = "%+.?f%c";
+
+ for (exp = 0; ABS(num) > 1000; exp += 3)
+ num /= 1000;
+
+ fmt[3] = (ABS(num) < 10) ? '3' : (ABS(num) < 100) ? '2' : '1';
+ if (exp == 0) {
+ fmt[5] = '\0';
+ fmt[3]++;
+ }
+ snprintf(str, len, fmt, num, label[exp / 3]);
+ if (num > 0)
+ str[0] = ' ';
+}
+
+int
+main()
+{
+ char str[8];
+
+ humanize(-1 << 18, str, sizeof(str));
+ printf("%s\n", str);
+
+ return 0;
+}