diff options
Diffstat (limited to 'core/string_helpers.hpp')
-rw-r--r-- | core/string_helpers.hpp | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/core/string_helpers.hpp b/core/string_helpers.hpp new file mode 100644 index 0000000..a35448b --- /dev/null +++ b/core/string_helpers.hpp @@ -0,0 +1,36 @@ +#ifndef M6lbZdsknZWfvEr3i3hoi7EZO8M +#define M6lbZdsknZWfvEr3i3hoi7EZO8M + +#include <math.h> +#include <sstream> +#include <string> + +template<int> struct SISuffix { }; + +const char microSISuffixName[6] = { 'm', '~', 'n', 'p', 'f', 'a' }; +const char macroSISuffixName[7] = { 'K', 'M', 'G', 'T', 'P', 'E', 'Y' }; + +int calcSISuffixId(double val, int base=1000) { + if (val >= base) return 1 + calcSISuffixId(val / base); + if (val < 1) return -1 + calcSISuffixId(val * base); + return 0; +} + +std::string SISuffixify(double val, int base=1000) { + int id = calcSISuffixId(val, base); + assert(id >= -6); + assert(id <= 7); + + std::ostringstream result; + + result << val / pow(base, id) << " "; + if (id < 0) + result << microSISuffixName[-id - 1]; + if (id > 0) + result << macroSISuffixName[ id - 1]; + + return result.str(); +} + + +#endif // M6lbZdsknZWfvEr3i3hoi7EZO8M |