From 881bb537c92684d25fae4fec9ac2dd61e1f9723c Mon Sep 17 00:00:00 2001 From: Ulf Hermann Date: Mon, 4 Jan 2016 13:05:51 +0100 Subject: Make RuntimeHelpers::numberToString() comply with EcmaScript We could use DoubleToStringConverter::EcmaScriptConverter().ToShortest() here, but we'd have to #ifdef it for the case that we're using the libc double conversion. As the formatting does not produce a lot of code I decided against that. Task-number: QTBUG-50131 Change-Id: If7a2ef8063b57ab35cda4a60d8ddd65442d70103 Reviewed-by: Lars Knoll --- src/qml/jsruntime/qv4runtime.cpp | 32 ++++++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) (limited to 'src/qml/jsruntime/qv4runtime.cpp') diff --git a/src/qml/jsruntime/qv4runtime.cpp b/src/qml/jsruntime/qv4runtime.cpp index 2d0eac079f..a1bcec4987 100644 --- a/src/qml/jsruntime/qv4runtime.cpp +++ b/src/qml/jsruntime/qv4runtime.cpp @@ -225,8 +225,36 @@ void RuntimeHelpers::numberToString(QString *result, double num, int radix) } if (radix == 10) { - const NumberLocale *locale = NumberLocale::instance(); - *result = locale->toString(num, 'g', locale->defaultDoublePrecision); + // We cannot use our usual locale->toString(...) here, because EcmaScript has special rules + // about the longest permissible number, depending on if it's <0 or >0. + const int ecma_shortest_low = -6; + const int ecma_shortest_high = 21; + + const QLatin1Char zero('0'); + const QLatin1Char dot('.'); + + int decpt = 0; + int sign = 0; + *result = qdtoa(num, &decpt, &sign); + + if (decpt <= ecma_shortest_low || decpt > ecma_shortest_high) { + if (result->length() > 1) + result->insert(1, dot); + result->append(QLatin1Char('e')); + if (decpt > 0) + result->append(QLatin1Char('+')); + result->append(QString::number(decpt - 1)); + } else if (decpt <= 0) { + result->prepend(QString::fromLatin1("0.%1").arg(QString().fill(zero, -decpt))); + } else if (decpt < result->length()) { + result->insert(decpt, dot); + } else { + result->append(QString().fill(zero, decpt - result->length())); + } + + if (sign) + result->prepend(QLatin1Char('-')); + return; } -- cgit v1.2.3