OSDN Git Service

fix compile problem
[tjqt4port/tj2qt4.git] / taskjuggler / RealFormat.cpp
1 /*
2  * RealFormat.cpp - TaskJuggler
3  *
4  * Copyright (c) 2001, 2002, 2003, 2004 by Chris Schlaeger <cs@kde.org>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of version 2 of the GNU General Public License as
8  * published by the Free Software Foundation.
9  *
10  * $Id$
11  */
12
13 #include "RealFormat.h"
14
15 #include <stdlib.h>
16 #include <math.h>
17
18 RealFormat::RealFormat(const QString& sp, const QString& ss,
19                        const QString& ts, const QString& fs, uint fd) :
20     signPrefix(sp),
21     signSuffix(ss),
22     thousandSep(ts),
23     fractionSep(fs),
24     fracDigits(fd)
25 {
26 }
27
28 RealFormat::RealFormat(const RealFormat& r) :
29     signPrefix(r.signPrefix),
30     signSuffix(r.signSuffix),
31     thousandSep(r.thousandSep),
32     fractionSep(r.fractionSep),
33     fracDigits(r.fracDigits)
34 {
35 }
36
37 QString
38 RealFormat::format(double val, bool showZeroFract) const
39 {
40     /* The algorithm further down does only truncation after fracDigits. So we
41      * have to do real rounding first. */
42     val = qRound(val * pow(10.0f, (int)fracDigits)) / pow(10.0f, (int)fracDigits);
43
44     QString text;
45     for (double v = fabs(val); v >= 1.0; v /= 1000)
46     {
47         if (!text.isEmpty())
48             text = thousandSep + text;
49         if (v >= 1000.0)
50             text = QString("%1").arg((int) v % 1000, 3) + text;
51         else
52             text = QString("%1").arg((int) v % 1000) + text;
53     }
54     if (text.isEmpty())
55         text = "0";
56     text.replace(QChar(' '), QChar('0'));
57     if (!fractionSep.isEmpty() && fracDigits > 0)
58     {
59         double v = fabs(val) - abs(static_cast<int>(val));
60         int fract = static_cast<int>(v * pow(10.0f, (int)fracDigits));
61         QString fracStr = QString("%1").arg(fract);
62         /* Prepend zeros if fractStr is not fracDigits long */
63         if (fracStr.length() < fracDigits)
64           fracStr = QString().fill('0', fracDigits - fracStr.length()) +
65               fracStr;
66         text += fractionSep + fracStr;
67         /* If showZeroFract is false, we remove all zeros from the right end
68          * of the text string. */
69         if (!showZeroFract)
70             while (text[text.length() - 1] == '0')
71                 text = text.left(text.length() - 1);
72         /* If we have removed the whole fractional part, we remove the
73          * fraction separator as well. */
74         if (text.right(fractionSep.length()) == fractionSep)
75             text = text.left(text.length() - fractionSep.length());
76     }
77     if (val < 0.0)
78         text = signPrefix + text + signSuffix;
79     return text;
80 }
81