add util::format_count

This commit is contained in:
MihailRis 2026-11-01 01:38:24 +03:00
parent d857e7326d
commit d4deb34722
2 changed files with 44 additions and 24 deletions

View file

@ -1,11 +1,11 @@
#include "stringutil.hpp"
#include <algorithm>
#include <charconv>
#include <cctype>
#include <cmath>
#include <iomanip>
#include <locale>
#include "stringutil.hpp"
#include <algorithm>
#include <charconv>
#include <cctype>
#include <cmath>
#include <iomanip>
#include <locale>
#include <sstream>
#include <stdexcept>
@ -511,22 +511,22 @@ int util::replaceAll(
return replace_all(str, from, to);
}
double util::parse_double(const std::string& str) {
const char* begin = str.data();
const char* end = begin + str.size();
while (begin != end && std::isspace(static_cast<unsigned char>(*begin))) {
begin++;
}
if (begin != end && *begin == '+') {
begin++;
}
double d = 0.0;
const auto result = std::from_chars(begin, end, d);
if (result.ec != std::errc()) {
throw std::runtime_error("invalid number format");
}
return d;
}
double util::parse_double(const std::string& str) {
const char* begin = str.data();
const char* end = begin + str.size();
while (begin != end && std::isspace(static_cast<unsigned char>(*begin))) {
begin++;
}
if (begin != end && *begin == '+') {
begin++;
}
double d = 0.0;
const auto result = std::from_chars(begin, end, d);
if (result.ec != std::errc()) {
throw std::runtime_error("invalid number format");
}
return d;
}
double util::parse_double(const std::string& str, size_t offset, size_t len) {
return parse_double(str.substr(offset, len));
@ -667,6 +667,25 @@ std::string util::format_data_size(size_t size) {
postfixes[group];
}
std::string util::format_count(size_t count) {
if (count < 1000) {
return std::to_string(count);
}
const std::string postfixes[] {
"", " K", " M", " B"
};
int group = 0;
size_t remainder = 0;
while (count >= 1000) {
group++;
remainder = count % 1000;
count /= 1000;
}
return std::to_string(count) + "." +
std::to_string(static_cast<int>(round(remainder / 1000.0f))) +
postfixes[group];
}
std::pair<std::string, std::string> util::split_at(
std::string_view view, char c
) {