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 <cstdint>
14#include <iomanip>
15#include <sstream>
16
17namespace tlx {
18
19//! Format number as something like 1 TB
20std::string format_si_units(std::uint64_t number, int precision) {
21 // may not overflow, std::numeric_limits<std::uint64_t>::max() == 16 EiB
22 double multiplier = 1000.0;
23 static const char* SI_endings[] = {
24 "", "k", "M", "G", "T", "P", "E"
25 };
26 unsigned int scale = 0;
27 double number_d = static_cast<double>(number);
28 while (number_d >= multiplier) {
29 number_d /= multiplier;
30 ++scale;
31 }
32 std::ostringstream out;
33 out << std::fixed << std::setprecision(precision) << number_d
34 << ' ' << SI_endings[scale];
35 return out.str();
36}
37
38//! Format number as something like 1 TiB
39std::string format_iec_units(std::uint64_t number, int precision) {
40 // may not overflow, std::numeric_limits<std::uint64_t>::max() == 16 EiB
41 double multiplier = 1024.0;
42 static const char* IEC_endings[] = {
43 "", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei"
44 };
45 unsigned int scale = 0;
46 double number_d = static_cast<double>(number);
47 while (number_d >= multiplier) {
48 number_d /= multiplier;
49 ++scale;
50 }
51 std::ostringstream out;
52 out << std::fixed << std::setprecision(precision) << number_d
53 << ' ' << IEC_endings[scale];
54 return out.str();
55}
56
57} // namespace tlx
58
59/******************************************************************************/
std::string format_iec_units(std::uint64_t number, int precision=3)
Format a byte size using IEC (Ki, Mi, Gi, Ti) suffixes (powers of two).
std::string format_si_units(std::uint64_t number, int precision)
Format number as something like 1 TB.