2 * RealFormat.cpp - TaskJuggler
4 * Copyright (c) 2001, 2002, 2003, 2004 by Chris Schlaeger <cs@kde.org>
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.
13 #include "RealFormat.h"
18 RealFormat::RealFormat(const QString& sp, const QString& ss,
19 const QString& ts, const QString& fs, uint fd) :
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)
38 RealFormat::format(double val, bool showZeroFract) const
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);
45 for (double v = fabs(val); v >= 1.0; v /= 1000)
48 text = thousandSep + text;
50 text = QString("%1").arg((int) v % 1000, 3) + text;
52 text = QString("%1").arg((int) v % 1000) + text;
56 text.replace(QChar(' '), QChar('0'));
57 if (!fractionSep.isEmpty() && fracDigits > 0)
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()) +
66 text += fractionSep + fracStr;
67 /* If showZeroFract is false, we remove all zeros from the right end
68 * of the text string. */
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());
78 text = signPrefix + text + signSuffix;