diff options
author | Ulf Hermann <ulf.hermann@theqtcompany.com> | 2015-10-16 16:52:51 +0200 |
---|---|---|
committer | Ulf Hermann <ulf.hermann@theqtcompany.com> | 2015-11-23 14:13:34 +0000 |
commit | 726fed0d67013cbfac7921d3d4613ca83406fb0f (patch) | |
tree | d8fd15a7d6416a91c150d6f2a3b0bdd98caa0d7f /src/corelib/tools/qlocale.cpp | |
parent | 04695c7a91bf2b7372bb5de5f8e0b5d6f7278f67 (diff) |
Interpret precision == -128 as "shortest" double conversion
Also use this for converting doubles with QVariant. We generally want
exact results there, rather than adding rounding errors whenever we
convert.
[ChangeLog][QtCore][QLocale] Added special value for double conversion
precision to get shortest accurate representation.
Change-Id: I905b8a103f39adf31d24b6ce2c8a283cf271b597
Reviewed-by: Lars Knoll <lars.knoll@theqtcompany.com>
Diffstat (limited to 'src/corelib/tools/qlocale.cpp')
-rw-r--r-- | src/corelib/tools/qlocale.cpp | 21 |
1 files changed, 18 insertions, 3 deletions
diff --git a/src/corelib/tools/qlocale.cpp b/src/corelib/tools/qlocale.cpp index dcb77a2c1b..072d62f5c2 100644 --- a/src/corelib/tools/qlocale.cpp +++ b/src/corelib/tools/qlocale.cpp @@ -2743,7 +2743,7 @@ QString QLocaleData::doubleToString(const QChar _zero, const QChar plus, const Q const QChar exponential, const QChar group, const QChar decimal, double d, int precision, DoubleForm form, int width, unsigned flags) { - if (precision < 0) + if (precision != QLocale::FloatingPointShortest && precision < 0) precision = 6; if (width < 0) width = 0; @@ -2753,7 +2753,9 @@ QString QLocaleData::doubleToString(const QChar _zero, const QChar plus, const Q int decpt; int bufSize = 1; - if (form == DFDecimal) // optimize for numbers smaller than 512k + if (precision == QLocale::FloatingPointShortest) + bufSize += DoubleMaxSignificant; + else if (form == DFDecimal) // optimize for numbers between -512k and 512k bufSize += ((d > (1 << 19) || d < -(1 << 19)) ? DoubleMaxDigitsBeforeDecimal : 6) + precision; else // Add extra digit due to different interpretations of precision. Also, "nan" has to fit. @@ -2798,7 +2800,20 @@ QString QLocaleData::doubleToString(const QChar _zero, const QChar plus, const Q PrecisionMode mode = (flags & Alternate) ? PMSignificantDigits : PMChopTrailingZeros; - if (decpt != digits.length() && (decpt <= -4 || decpt > precision)) + int cutoff = precision < 0 ? 6 : precision; + // Find out which representation is shorter + if (precision == QLocale::FloatingPointShortest && decpt > 0) { + cutoff = digits.length() + 4; // 'e', '+'/'-', one digit exponent + if (decpt <= 10) { + ++cutoff; + } else { + cutoff += decpt > 100 ? 2 : 1; + } + if (!always_show_decpt && digits.length() > decpt) + ++cutoff; // decpt shown in exponent form, but not in decimal form + } + + if (decpt != digits.length() && (decpt <= -4 || decpt > cutoff)) num_str = exponentForm(_zero, decimal, exponential, group, plus, minus, digits, decpt, precision, mode, always_show_decpt); |