X-Git-Url: https://sigrok.org/gitweb/?p=pulseview.git;a=blobdiff_plain;f=pv%2Futil.cpp;h=9a9a5065a2e17180eb6cdebb71b4aefc07fb5833;hp=8f2d7d2544cd8e30301a28c56f6537269dbe759a;hb=66279897e318a2549557054d1204c862f7d99469;hpb=aca9aa834c742ba70f49d1ac3eb2d1e02e759416 diff --git a/pv/util.cpp b/pv/util.cpp index 8f2d7d25..9a9a5065 100644 --- a/pv/util.cpp +++ b/pv/util.cpp @@ -138,8 +138,47 @@ QString format_time_si(const Timestamp& v, SIPrefix prefix, QTextStream ts(&s); if (sign && !v.is_zero()) ts << forcesign; - ts << qSetRealNumberPrecision(precision) << (v * multiplier) << ' ' - << prefix << unit; + ts << qSetRealNumberPrecision(precision) << (v * multiplier); + ts << ' ' << prefix << unit; + + return s; +} + +QString format_value_si(double v, SIPrefix prefix, unsigned precision, + QString unit, bool sign) +{ + if (prefix == SIPrefix::unspecified) { + // No prefix given, calculate it + + if (v == 0) { + prefix = SIPrefix::none; + } else { + int exp = exponent(SIPrefix::yotta); + prefix = SIPrefix::yocto; + while ((fabs(v) * pow(Timestamp(10), exp)) > 999 && + prefix < SIPrefix::yotta) { + prefix = successor(prefix); + exp -= 3; + } + } + + const int prefix_order = -exponent(prefix); + precision = (prefix >= SIPrefix::none) ? max((int)(precision + prefix_order), 0) : + max((int)(precision - prefix_order), 0); + } + + assert(prefix >= SIPrefix::yocto); + assert(prefix <= SIPrefix::yotta); + + const double multiplier = pow(10.0, -exponent(prefix)); + + QString s; + QTextStream ts(&s); + if (sign && (v != 0)) + ts << forcesign; + ts.setRealNumberNotation(QTextStream::FixedNotation); + ts.setRealNumberPrecision(precision); + ts << (v * multiplier) << ' ' << prefix << unit; return s; } @@ -224,5 +263,27 @@ QString format_time_minutes(const Timestamp& t, signed precision, bool sign) return s; } +/** + * Split a string into tokens at occurences of the separator. + * + * @param[in] text The input string to split. + * @param[in] separator The delimiter between tokens. + * + * @return A vector of broken down tokens. + */ +vector split_string(string text, string separator) +{ + vector result; + size_t pos; + + while ((pos = text.find(separator)) != std::string::npos) { + result.push_back(text.substr(0, pos)); + text = text.substr(pos + separator.length()); + } + result.push_back(text); + + return result; +} + } // namespace util } // namespace pv