humanize a number for the scale - ploot - simple plotting tools | |
git clone git://bitreich.org/ploot git://enlrupgkhuxnvlhsf6lc3fziv5h2hhfrinws65… | |
Log | |
Files | |
Refs | |
Tags | |
README | |
LICENSE | |
--- | |
commit 04a8bcf172e92e0f70bc889b5181bc3cbdb8f381 | |
Author: Josuah Demangeon <[email protected]> | |
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(-) | |
--- | |
diff --git a/.gitignore b/.gitignore | |
@@ -0,0 +1,2 @@ | |
+*.o | |
+./plot | |
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 | |
diff --git a/plot b/plot | |
Binary files differ. | |
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; | |
+} |