Changed nice_unit_format() to allow selection between SI and IEC Systems of Units
authorGuilherme Maciel Ferreira <guilherme.maciel.ferreira@intra2net.com>
Mon, 31 Jan 2011 17:30:31 +0000 (18:30 +0100)
committerGuilherme Maciel Ferreira <guilherme.maciel.ferreira@intra2net.com>
Mon, 31 Jan 2011 17:30:31 +0000 (18:30 +0100)
- SI allows multiples of decimal 1000 (nice_unit_format default behavior)
- IEC allows multiples of binary 1024, 2^10 (format_kb default behavior)

src/stringfunc.cpp
src/stringfunc.hxx

index e3e99cd..f0b2585 100644 (file)
@@ -892,22 +892,36 @@ string to_upper(const string &src)
 }
 #endif
 
-string nice_unit_format(const int64_t input)
+string nice_unit_format(
+        const int64_t input,
+        const UnitSystem system
+)
 {
-   double size = input;
+   int multiple = 0;
+
+   if (system == SI)
+   {
+       multiple = 1000;
+   }
+   else
+   {
+       multiple = 1024;
+   }
+
+   long double size = input;
    int sizecount = 0;
 
-   while (size > 1000)
+   while (size > multiple)
    {
-      size = size / 1000;
-      sizecount++;
+       size = size / multiple;
+       sizecount++;
    }
 
-   double tmp;                       // round
-   tmp = size*10;
+   long double tmp;                       // round
+   tmp = size * 10;
    tmp += 0.5;
    tmp = (int64_t) (tmp);
-   tmp = double (tmp) /double (10);
+   tmp = (long double) (tmp) / (long double) (10);
    size = tmp;
 
    ostringstream out;
index 85acdce..0423afd 100644 (file)
@@ -191,7 +191,16 @@ using I2n::to_lower;
 using I2n::to_upper;
 #endif
 
-std::string nice_unit_format(const int64_t input);
+
+enum UnitSystem {
+    SI, // SI decimal, composed by multiples of 1000 (KB, MB, etc.)
+    IEC // IEC binary, composed by multiples of 1024 (KiB, MiB, etc. )
+};
+
+std::string nice_unit_format(
+        const int64_t input,
+        const UnitSystem system = SI
+);
 
 bool replace_all(std::string &base, const std::string *ist, const std::string *soll);
 bool replace_all(std::string &base, const char *ist, const char *soll);