From 07b94c9f327c0b3230022b55f8105249f205a739 Mon Sep 17 00:00:00 2001 From: Karel Zak Date: Tue, 12 Feb 2019 13:27:56 +0100 Subject: [PATCH] lib/strutils: support two decimal places in size_to_human_string() output Signed-off-by: Karel Zak --- include/strutils.h | 7 ++++--- lib/strutils.c | 15 +++++++++++---- 2 files changed, 15 insertions(+), 7 deletions(-) diff --git a/include/strutils.h b/include/strutils.h index 0c4679882..65d5259db 100644 --- a/include/strutils.h +++ b/include/strutils.h @@ -121,9 +121,10 @@ extern char *xstrmode(mode_t mode, char *str); /* Options for size_to_human_string() */ enum { - SIZE_SUFFIX_1LETTER = 0, - SIZE_SUFFIX_3LETTER = 1, - SIZE_SUFFIX_SPACE = 2 + SIZE_SUFFIX_1LETTER = 0, + SIZE_SUFFIX_3LETTER = (1 << 0), + SIZE_SUFFIX_SPACE = (1 << 1), + SIZE_DECIMAL_2DIGITS = (1 << 2) }; extern char *size_to_human_string(int options, uint64_t bytes); diff --git a/lib/strutils.c b/lib/strutils.c index b71dde596..369d50159 100644 --- a/lib/strutils.c +++ b/lib/strutils.c @@ -551,6 +551,7 @@ char *size_to_human_string(int options, uint64_t bytes) if (options & SIZE_SUFFIX_SPACE) *psuf++ = ' '; + exp = get_exp(bytes); c = *(letters + (exp ? exp / 10 : 0)); dec = exp ? bytes / (1ULL << exp) : bytes; @@ -569,11 +570,17 @@ char *size_to_human_string(int options, uint64_t bytes) * exp, suffix[0], dec, frac); */ + /* round */ if (frac) { - /* round */ - frac = (frac / (1ULL << (exp - 10)) + 50) / 100; - if (frac == 10) - dec++, frac = 0; + if (options & SIZE_DECIMAL_2DIGITS) { + frac = (frac / (1ULL << (exp - 10)) + 5) / 10; + if (frac % 10 == 0) + frac /= 10; /* convert N.90 to N.9 */ + } else { + frac = (frac / (1ULL << (exp - 10)) + 50) / 100; + if (frac == 10) + dec++, frac = 0; + } } if (frac) {