util: Added format_si_value
[pulseview.git] / pv / util.cpp
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
30 using namespace Qt;
31
32 namespace pv {
33 namespace util {
34
35 static const QString SIPrefixes[9] =
36         {"f", "p", "n", QChar(0x03BC), "m", "", "k", "M", "G"};
37 const int FirstSIPrefixPower = -15;
38
39 QString format_si_value(double v, QString unit, int prefix,
40         unsigned int precision, bool sign)
41 {
42         if (prefix < 0) {
43                 int exp = -FirstSIPrefixPower;
44
45                 prefix = 0;
46                 while ((fabs(v) * pow(10.0, exp)) > 999.0 &&
47                         prefix < (int)(countof(SIPrefixes) - 1)) {
48                         prefix++;
49                         exp -= 3;
50                 }
51         }
52
53         assert(prefix >= 0);
54         assert(prefix < countof(SIPrefixes));
55
56         const double multiplier = pow(10.0,
57                 (int)- prefix * 3 - FirstSIPrefixPower);
58
59         QString s;
60         QTextStream ts(&s);
61         if (sign)
62                 ts << forcesign;
63         ts << fixed << qSetRealNumberPrecision(precision)
64                 << (v  * multiplier) << SIPrefixes[prefix] << unit;
65
66         return s;
67 }
68
69 QString format_time(double t, int prefix,
70         unsigned int precision, bool sign)
71 {
72         return format_si_value(t, "s", prefix, precision, sign);
73 }
74
75 QString format_second(double second)
76 {
77         return format_si_value(second, "s", -1, 0, false);
78 }
79
80 } // namespace util
81 } // namespace pv