48 lines
1.4 KiB
C++
48 lines
1.4 KiB
C++
|
#include <cstdio>
|
||
|
#include <cmath>
|
||
|
#include "helpers.h"
|
||
|
|
||
|
char * strip_eol (char * str) {
|
||
|
char * ptr = str;
|
||
|
for (;;) {
|
||
|
const char c = * ptr;
|
||
|
if (c == '\0') break;
|
||
|
else if (c == '\r') * ptr = '\0';
|
||
|
else if (c == '\n') * ptr = '\0';
|
||
|
ptr++;
|
||
|
}
|
||
|
return str;
|
||
|
}
|
||
|
std::string ing_fmt (const double par, const unsigned dnum) {
|
||
|
const char * suffixes [] = {"a", "f", "p", "n", "μ", "m", " ", "k", "M", "G", "T", "P", "E"};
|
||
|
bool sign = false;
|
||
|
double value = par;
|
||
|
if (par < 0.0) {
|
||
|
value = - par;
|
||
|
sign = true;
|
||
|
}
|
||
|
if (value < 1.0e-18) return std::string ("0");
|
||
|
if (value > 1.0e+18) return std::string ("hafo");
|
||
|
|
||
|
const double dlog = log10 (value) + 18.0;
|
||
|
double fractional, integer;
|
||
|
fractional = modf (dlog, & integer);
|
||
|
const double mult = pow (10.0, double (dnum - 1));
|
||
|
double avgf = pow (10.0, fractional); // do mezí 1.0 až 9.9999...
|
||
|
avgf *= mult;
|
||
|
avgf = round (avgf); // a teď zaokrouhli
|
||
|
avgf /= mult;
|
||
|
div_t dt = div (int(integer), 3);
|
||
|
avgf *= pow (10.0, double (dt.rem));
|
||
|
// printf("%g:%g (%f) [%d:%d]{%s}\n", integer, fractional, avgf, dt.quot, dt.rem, suffixes[dt.quot]);
|
||
|
|
||
|
const unsigned buflen = 64;
|
||
|
char buffer [buflen];
|
||
|
const int r = snprintf(buffer, buflen, "%g%s", avgf, suffixes [dt.quot]);
|
||
|
buffer [r] = '\0';
|
||
|
|
||
|
std::string result (buffer, r);
|
||
|
if (sign) result = std::string("-") + result;
|
||
|
return result;
|
||
|
}
|