commit: 849336603e6db53876692df41c96bf403cf8ed38
parent ea7360c37dd40b1aca6456566cf4c32ba03c2bf9
Author: Haelwenn (lanodan) Monnier <contact@hacktivis.me>
Date: Thu, 17 Apr 2025 01:31:30 +0200
cmd/humanize: handle negative values
Diffstat:
2 files changed, 20 insertions(+), 0 deletions(-)
diff --git a/cmd/humanize.c b/cmd/humanize.c
@@ -21,6 +21,13 @@ human_num(long double num, bool iec)
unsigned div = iec ? 1024 : 1000;
char **prefixes = iec ? iec_prefixes : si_prefixes;
+ bool neg = false;
+ if(num < 0)
+ {
+ neg = true;
+ num = -num;
+ }
+
unsigned quotient = 0;
while(num > div && quotient < (PFX - 1))
{
@@ -28,6 +35,8 @@ human_num(long double num, bool iec)
quotient += 1;
}
+ if(neg) num = -num;
+
// %g to avoid decimal separator when possible, %f to avoid %e exponent form
printf((num > div ? "%Lf %s\n" : "%Lg %s\n"), num, prefixes[quotient]);
}
diff --git a/test-cmd/humanize b/test-cmd/humanize
@@ -77,6 +77,15 @@ pfx_limit_body() {
atf_check -o "inline:1000000.000000 Q\n" ../cmd/humanize "$(echo 1000^12 | bc -l)"
}
+atf_test_case neg
+neg_body() {
+ atf_check -o "inline:-1000 \n" ../cmd/humanize -- -1000
+ atf_check -o "inline:-1024 B\n" ../cmd/humanize -b -- -1024
+
+ atf_check -o "inline:-1000 k\n" ../cmd/humanize -- -1000000
+ atf_check -o "inline:-1024 KiB\n" ../cmd/humanize -b -- -1048576
+}
+
atf_test_case duration
duration_body() {
atf_check -o "inline:1s\n" ../cmd/humanize -t 1
@@ -104,5 +113,7 @@ atf_init_test_cases() {
atf_add_test_case pfx_limit
+ atf_add_test_case neg
+
atf_add_test_case duration
}