-
Notifications
You must be signed in to change notification settings - Fork 0
/
format_legible.h
79 lines (72 loc) · 2.33 KB
/
format_legible.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#pragma once
#include <iomanip>
#include <locale>
#include <sstream>
#include <string>
#include "map_positivepowerprefix.h"
namespace format_legible
{
constexpr int KiloBreak { 1024 };
// returns numbers greater than KiloBreak as human-readable numbers with commonly accepted prefixes
// ex: 1073741824 returns "1 GB"
// - SourceNumber: numeric raw value
// - Precision: maximum number of decimal places in output string. default: 1
template <typename T>
std::string FriendlyFormatBytes(T SourceNumber, std::streamsize Precision = 1)
{
std::stringstream NumberStream;
NumberStream << std::fixed;
auto KiloBreaks = 0;
if (SourceNumber <= KiloBreak)
{
NumberStream << SourceNumber;
}
else
{
NumberStream.precision(Precision);
auto TranslatedNumber = SourceNumber / 1.0;
while (TranslatedNumber > KiloBreak || TranslatedNumber < -KiloBreak)
{
++KiloBreaks;
TranslatedNumber /= KiloBreak;
}
NumberStream.imbue(std::locale(""));
std::use_facet<std::num_put<char>>(NumberStream.getloc()).put(NumberStream, NumberStream, '0', TranslatedNumber);
}
const char prefix{ map_positivepowerprefix::GetPrefixByKiloPosition(KiloBreaks) };
NumberStream << std::setw(prefix == ' ' ? 1 : 2);
NumberStream << prefix;
NumberStream << 'B';
return NumberStream.str();
}
// returns any number as a percentage in string format
// prevents breaking into scientific notation
// - Percentage: raw number
// - Precision: maximum number of decimal places in output string. default: 1
template <typename T>
std::string FriendlyFormatPercentage(T Percentage, std::streamsize Precision = 1)
{
std::stringstream NumberStream;
NumberStream << std::fixed;
NumberStream.precision(Precision);
NumberStream << Percentage << '%';
return NumberStream.str();
}
// returns a string representing Value's percent of Total
// ex: Value 23, Total 100 returns "23%"
// - Value: value to calculate as percentage against Total
// - Total: total number that Value is a percentage of
// - Precision: maximum number of decimal places in output string. default: 1
template <typename T, typename U>
std::string FriendlyFormatCalculatedPercentage(T Value, U Total, std::streamsize Precision = 1)
{
if (Total)
{
return FriendlyFormatPercentage(1.0 * Value / Total * 100, Precision);
}
else
{
return std::string("nan%");
}
}
}