X-Git-Url: https://sigrok.org/gitweb/?a=blobdiff_plain;f=pv%2Futil.cpp;h=897254e12160fa59e60c7766efbd5e84f1d5fff5;hb=e23d7aa0d9980c3c269cbddb4cfbb32350d7425c;hp=6424a9b1b5893b13d212ad1deef61221bea30aef;hpb=3083cda853bd12d73b741c3bc97b70f5d395a15a;p=pulseview.git diff --git a/pv/util.cpp b/pv/util.cpp index 6424a9b1..897254e1 100644 --- a/pv/util.cpp +++ b/pv/util.cpp @@ -110,25 +110,31 @@ static QTextStream& operator<<(QTextStream& stream, const Timestamp& t) return stream << QString::fromStdString(str); } -QString format_time_si(const Timestamp& v, SIPrefix prefix, - unsigned int precision, QString unit, bool sign) +SIPrefix determine_value_prefix(double v) { - if (prefix == SIPrefix::unspecified) { - // No prefix given, calculate it - - if (v.is_zero()) { - 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; - } + SIPrefix prefix; + + if (v == 0) { + prefix = SIPrefix::none; + } else { + int exp = exponent(SIPrefix::yotta); + prefix = SIPrefix::yocto; + while ((fabs(v) * pow(10, exp)) > 999 && + prefix < SIPrefix::yotta) { + prefix = successor(prefix); + exp -= 3; } } + return prefix; +} + +QString format_time_si(const Timestamp& v, SIPrefix prefix, + unsigned int precision, QString unit, bool sign) +{ + if (prefix == SIPrefix::unspecified) + prefix = determine_value_prefix(v.convert_to()); + assert(prefix >= SIPrefix::yocto); assert(prefix <= SIPrefix::yotta); @@ -138,8 +144,35 @@ 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) { + prefix = determine_value_prefix(v); + + 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; }