]> sigrok.org Git - pulseview.git/blame_incremental - pv/util.cpp
util: Fixed assertion
[pulseview.git] / pv / util.cpp
... / ...
CommitLineData
1/*
2 * This file is part of the PulseView project.
3 *
4 * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 */
20
21#include "util.hpp"
22
23#include <extdef.h>
24
25#include <assert.h>
26
27#include <QTextStream>
28#include <QDebug>
29
30using namespace Qt;
31
32namespace pv {
33namespace util {
34
35static const QString SIPrefixes[17] =
36 {"y", "z", "a", "f", "p", "n", QChar(0x03BC), "m", "", "k", "M", "G",
37 "T", "P", "E", "Z", "Y"};
38const int FirstSIPrefixPower = -24;
39
40QString format_si_value(double v, QString unit, int prefix,
41 unsigned int precision, bool sign)
42{
43 if (prefix < 0) {
44 int exp = -FirstSIPrefixPower;
45
46 prefix = 0;
47 while ((fabs(v) * pow(10.0, exp)) > 999.0 &&
48 prefix < (int)(countof(SIPrefixes) - 1)) {
49 prefix++;
50 exp -= 3;
51 }
52 }
53
54 assert(prefix >= 0);
55 assert(prefix < (int)countof(SIPrefixes));
56
57 const double multiplier = pow(10.0,
58 (int)- prefix * 3 - FirstSIPrefixPower);
59
60 QString s;
61 QTextStream ts(&s);
62 if (sign)
63 ts << forcesign;
64 ts << fixed << qSetRealNumberPrecision(precision) <<
65 (v * multiplier) << " " << SIPrefixes[prefix] << unit;
66
67 return s;
68}
69
70QString format_time(double t, int prefix,
71 unsigned int precision, bool sign)
72{
73 return format_si_value(t, "s", prefix, precision, sign);
74}
75
76QString format_second(double second)
77{
78 return format_si_value(second, "s", -1, 0, false);
79}
80
81} // namespace util
82} // namespace pv