tlx
Loading...
Searching...
No Matches
format_si_iec_units.cpp
Go to the documentation of this file.
1/*******************************************************************************
2 * tlx/string/format_si_iec_units.cpp
3 *
4 * Part of tlx - http://panthema.net/tlx
5 *
6 * Copyright (C) 2016-2017 Timo Bingmann <tb@panthema.net>
7 *
8 * All rights reserved. Published under the Boost Software License, Version 1.0
9 ******************************************************************************/
10
12
13#include <iomanip>
14#include <sstream>
15
16namespace tlx {
17
18//! Format number as something like 1 TB
19std::string format_si_units(uint64_t number, int precision) {
20 // may not overflow, std::numeric_limits<uint64_t>::max() == 16 EiB
21 double multiplier = 1000.0;
22 static const char* SI_endings[] = {
23 "", "k", "M", "G", "T", "P", "E"
24 };
25 unsigned int scale = 0;
26 double number_d = static_cast<double>(number);
27 while (number_d >= multiplier) {
28 number_d /= multiplier;
29 ++scale;
30 }
31 std::ostringstream out;
32 out << std::fixed << std::setprecision(precision) << number_d
33 << ' ' << SI_endings[scale];
34 return out.str();
35}
36
37//! Format number as something like 1 TiB
38std::string format_iec_units(uint64_t number, int precision) {
39 // may not overflow, std::numeric_limits<uint64_t>::max() == 16 EiB
40 double multiplier = 1024.0;
41 static const char* IEC_endings[] = {
42 "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"
43 };
44 unsigned int scale = 0;
45 double number_d = static_cast<double>(number);
46 while (number_d >= multiplier) {
47 number_d /= multiplier;
48 ++scale;
49 }
50 std::ostringstream out;
51 out << std::fixed << std::setprecision(precision) << number_d
52 << ' ' << IEC_endings[scale];
53 return out.str();
54}
55
56} // namespace tlx
57
58/******************************************************************************/
std::string format_si_units(uint64_t number, int precision)
Format number as something like 1 TB.
std::string format_iec_units(uint64_t number, int precision=3)
Format a byte size using IEC (Ki, Mi, Gi, Ti) suffixes (powers of two).