forked from battlesnake/tun-example
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathformat_si.cpp
More file actions
69 lines (59 loc) · 1.57 KB
/
format_si.cpp
File metadata and controls
69 lines (59 loc) · 1.57 KB
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
#include <cmath>
#include <sstream>
#include <iomanip>
#include "format_si.hpp"
using namespace std;
const string prefixes = "yzafpnum kMGTPEZY";
string format_si(float value, const string& base_unit, int digits)
{
int l1000 = value == 0 ? 0 : floor(log10(abs(value)) / 3);
int iprefix = max(min(l1000 + 8, (int) prefixes.length() - 1), 0);
value *= pow(1000, -(iprefix - 8));
char prefix = prefixes[iprefix];
ostringstream oss;
if (abs(value) < 1 && value != 0) {
oss.setf(ios::scientific, ios::floatfield);
oss.precision(digits);
} else {
oss.setf(ios::fixed, ios::floatfield);
int places = digits - (value == 0 ? 0 : floor(log10(abs(value)))) - 1;
oss.precision(places);
}
oss << value;
if (prefix != ' ') {
oss << prefix;
}
oss << base_unit;
return oss.str();
}
__attribute__((__unused__))
static void test(ostream& os)
{
#define test(value, base, digits) \
os << "format_si(" << value << ", " << base << ", " << digits << ") ==> " << format_si(value, base, digits) << std::endl;
os.precision(6);
os.setf(std::ios::fixed, std::ios::floatfield);
test(0, "Ω", 6);
test(0, "Ω", 3);
test(0, "Ω", 1);
test(1, "Ω", 6);
test(1, "Ω", 3);
test(1, "Ω", 1);
test(-1, "Ω", 6);
test(-1, "Ω", 3);
test(-1, "Ω", 1);
test(0.00001234, "Ω", 3);
test(0.0001234, "Ω", 3);
test(0.001234, "Ω", 3);
test(0.01234, "Ω", 3);
test(0.1234, "Ω", 3);
test(1.234, "Ω", 3);
test(12.34, "Ω", 3);
test(123.4, "Ω", 3);
test(1234, "Ω", 3);
test(12340, "Ω", 3);
test(123400, "Ω", 3);
test(1234000, "Ω", 3);
test(12340000, "Ω", 3);
test(123400000, "Ω", 3);
}