1 /****************************************************************************
3 ** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
6 ** This file is part of the QtCore module of the Qt Toolkit.
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
40 ****************************************************************************/
42 #if !defined(QWS) && defined(Q_OS_MAC)
43 # include "private/qcore_mac_p.h"
44 # include <CoreFoundation/CoreFoundation.h>
49 #include "qplatformdefs.h"
51 #include "qdatastream.h"
55 #include "qlocale_p.h"
56 #include "qlocale_tools_p.h"
57 #include "qdatetime_p.h"
58 #include "qnamespace.h"
59 #include "qdatetime.h"
60 #include "qstringlist.h"
62 #include "qstringbuilder.h"
63 #include "private/qnumeric_p.h"
64 #include "private/qsystemlibrary_p.h"
66 # include <qt_windows.h>
72 #ifndef QT_NO_SYSTEMLOCALE
73 static QSystemLocale *_systemLocale = 0;
74 class QSystemLocaleSingleton: public QSystemLocale
77 QSystemLocaleSingleton() : QSystemLocale(true) {}
80 Q_GLOBAL_STATIC(QSystemLocaleSingleton, QSystemLocale_globalSystemLocale)
81 static QLocaleData *system_data = 0;
82 Q_GLOBAL_STATIC(QLocaleData, globalLocaleData)
85 /******************************************************************************
86 ** Helpers for accessing Qt locale database
89 QT_BEGIN_INCLUDE_NAMESPACE
90 #include "qlocale_data_p.h"
91 QT_END_INCLUDE_NAMESPACE
93 QLocale::Language QLocalePrivate::codeToLanguage(const QString &code)
95 int len = code.length();
96 if (len != 2 && len != 3)
98 ushort uc1 = len-- > 0 ? code[0].toLower().unicode() : 0;
99 ushort uc2 = len-- > 0 ? code[1].toLower().unicode() : 0;
100 ushort uc3 = len-- > 0 ? code[2].toLower().unicode() : 0;
102 const unsigned char *c = language_code_list;
103 for (; *c != 0; c += 3) {
104 if (uc1 == c[0] && uc2 == c[1] && uc3 == c[2])
105 return QLocale::Language((c - language_code_list)/3);
109 if (uc1 == 'n' && uc2 == 'o' && uc3 == 0) { // no -> nb
110 Q_STATIC_ASSERT(QLocale::Norwegian == QLocale::NorwegianBokmal);
111 return QLocale::Norwegian;
113 if (uc1 == 't' && uc2 == 'l' && uc3 == 0) { // tl -> fil
114 Q_STATIC_ASSERT(QLocale::Tagalog == QLocale::Filipino);
115 return QLocale::Tagalog;
117 if (uc1 == 's' && uc2 == 'h' && uc3 == 0) { // sh -> sr[_Latn]
118 Q_STATIC_ASSERT(QLocale::SerboCroatian == QLocale::Serbian);
119 return QLocale::SerboCroatian;
121 if (uc1 == 'm' && uc2 == 'o' && uc3 == 0) { // mo -> ro
122 Q_STATIC_ASSERT(QLocale::Moldavian == QLocale::Romanian);
123 return QLocale::Moldavian;
129 QLocale::Script QLocalePrivate::codeToScript(const QString &code)
131 int len = code.length();
133 return QLocale::AnyScript;
135 // script is titlecased in our data
136 unsigned char c0 = code.at(0).toUpper().toLatin1();
137 unsigned char c1 = code.at(1).toLower().toLatin1();
138 unsigned char c2 = code.at(2).toLower().toLatin1();
139 unsigned char c3 = code.at(3).toLower().toLatin1();
141 const unsigned char *c = script_code_list;
142 for (int i = 0; i < QLocale::LastScript; ++i, c += 4) {
143 if (c0 == c[0] && c1 == c[1] && c2 == c[2] && c3 == c[3])
144 return QLocale::Script(i);
146 return QLocale::AnyScript;
149 QLocale::Country QLocalePrivate::codeToCountry(const QString &code)
151 int len = code.length();
152 if (len != 2 && len != 3)
153 return QLocale::AnyCountry;
154 ushort uc1 = len-- > 0 ? code[0].toUpper().unicode() : 0;
155 ushort uc2 = len-- > 0 ? code[1].toUpper().unicode() : 0;
156 ushort uc3 = len-- > 0 ? code[2].toUpper().unicode() : 0;
158 const unsigned char *c = country_code_list;
159 for (; *c != 0; c += 3) {
160 if (uc1 == c[0] && uc2 == c[1] && uc3 == c[2])
161 return QLocale::Country((c - country_code_list)/3);
164 return QLocale::AnyCountry;
167 QString QLocalePrivate::languageCode() const
169 if (m_data->m_language_id == QLocale::AnyLanguage)
171 if (m_data->m_language_id == QLocale::C)
172 return QLatin1String("C");
174 const unsigned char *c = language_code_list + 3*(uint(m_data->m_language_id));
176 QString code(c[2] == 0 ? 2 : 3, Qt::Uninitialized);
178 code[0] = ushort(c[0]);
179 code[1] = ushort(c[1]);
181 code[2] = ushort(c[2]);
186 QString QLocalePrivate::scriptCode() const
188 if (m_data->m_script_id == QLocale::AnyScript || m_data->m_script_id > QLocale::LastScript)
190 const unsigned char *c = script_code_list + 4*(uint(m_data->m_script_id));
191 return QString::fromLatin1((const char *)c, 4);
194 QString QLocalePrivate::countryCode() const
196 if (m_data->m_country_id == QLocale::AnyCountry)
199 const unsigned char *c = country_code_list + 3*(uint(m_data->m_country_id));
201 QString code(c[2] == 0 ? 2 : 3, Qt::Uninitialized);
203 code[0] = ushort(c[0]);
204 code[1] = ushort(c[1]);
206 code[2] = ushort(c[2]);
211 // http://www.unicode.org/reports/tr35/#Likely_Subtags
212 static bool addLikelySubtags(QLocaleId &localeId)
214 // ### optimize with bsearch
215 const int likely_subtags_count = sizeof(likely_subtags) / sizeof(likely_subtags[0]);
216 const QLocaleId *p = likely_subtags;
217 const QLocaleId *const e = p + likely_subtags_count;
218 for ( ; p < e; p += 2) {
219 if (localeId == p[0]) {
227 QLocaleId QLocaleId::withLikelySubtagsAdded() const
229 // language_script_region
230 if (language_id || script_id || country_id) {
231 QLocaleId id = QLocaleId::fromIds(language_id, script_id, country_id);
232 if (addLikelySubtags(id))
237 QLocaleId id = QLocaleId::fromIds(language_id, script_id, 0);
238 if (addLikelySubtags(id)) {
239 id.country_id = country_id;
245 QLocaleId id = QLocaleId::fromIds(language_id, 0, country_id);
246 if (addLikelySubtags(id)) {
247 id.script_id = script_id;
252 if (script_id && country_id) {
253 QLocaleId id = QLocaleId::fromIds(language_id, 0, 0);
254 if (addLikelySubtags(id)) {
255 id.script_id = script_id;
256 id.country_id = country_id;
263 QLocaleId QLocaleId::withLikelySubtagsRemoved() const
265 QLocaleId max = withLikelySubtagsAdded();
268 QLocaleId id = QLocaleId::fromIds(language_id, 0, 0);
269 if (id.withLikelySubtagsAdded() == max)
274 QLocaleId id = QLocaleId::fromIds(language_id, 0, country_id);
275 if (id.withLikelySubtagsAdded() == max)
280 QLocaleId id = QLocaleId::fromIds(language_id, script_id, 0);
281 if (id.withLikelySubtagsAdded() == max)
287 QString QLocaleId::bcp47Name() const
289 if (language_id == QLocale::AnyLanguage)
291 if (language_id == QLocale::C)
292 return QStringLiteral("C");
294 const unsigned char *lang = language_code_list + 3*uint(language_id);
295 const unsigned char *script =
296 (script_id != QLocale::AnyScript ? script_code_list + 4*uint(script_id) : 0);
297 const unsigned char *country =
298 (country_id != QLocale::AnyCountry ? country_code_list + 3*uint(country_id) : 0);
299 char len = (lang[2] != 0 ? 3 : 2) + (script ? 4+1 : 0) + (country ? (country[2] != 0 ? 3 : 2)+1 : 0);
300 QString name(len, Qt::Uninitialized);
301 QChar *uc = name.data();
302 *uc++ = ushort(lang[0]);
303 *uc++ = ushort(lang[1]);
305 *uc++ = ushort(lang[2]);
307 *uc++ = QLatin1Char('-');
308 *uc++ = ushort(script[0]);
309 *uc++ = ushort(script[1]);
310 *uc++ = ushort(script[2]);
311 *uc++ = ushort(script[3]);
314 *uc++ = QLatin1Char('-');
315 *uc++ = ushort(country[0]);
316 *uc++ = ushort(country[1]);
318 *uc++ = ushort(country[2]);
323 QString QLocalePrivate::bcp47Name() const
325 if (m_data->m_language_id == QLocale::AnyLanguage)
327 if (m_data->m_language_id == QLocale::C)
328 return QStringLiteral("C");
330 QLocaleId localeId = QLocaleId::fromIds(m_data->m_language_id, m_data->m_script_id, m_data->m_country_id);
331 return localeId.withLikelySubtagsRemoved().bcp47Name();
334 const QLocaleData *QLocaleData::findLocaleData(QLocale::Language language, QLocale::Script script, QLocale::Country country)
336 QLocaleId localeId = QLocaleId::fromIds(language, script, country);
337 localeId = localeId.withLikelySubtagsAdded();
339 uint idx = locale_index[localeId.language_id];
341 const QLocaleData *data = locale_data + idx;
343 if (idx == 0) // default language has no associated country
346 Q_ASSERT(data->m_language_id == localeId.language_id);
348 if (localeId.script_id != QLocale::AnyScript && localeId.country_id != QLocale::AnyCountry) {
349 // both script and country are explicitly specified
351 if (data->m_script_id == localeId.script_id && data->m_country_id == localeId.country_id)
354 } while (data->m_language_id == localeId.language_id);
356 // no match; try again with default script
357 localeId.script_id = QLocale::AnyScript;
358 data = locale_data + idx;
361 if (localeId.script_id == QLocale::AnyScript && localeId.country_id == QLocale::AnyCountry)
364 if (localeId.script_id == QLocale::AnyScript) {
366 if (data->m_country_id == localeId.country_id)
369 } while (data->m_language_id == localeId.language_id);
370 } else if (localeId.country_id == QLocale::AnyCountry) {
372 if (data->m_script_id == localeId.script_id)
375 } while (data->m_language_id == localeId.language_id);
378 return locale_data + idx;
381 static bool parse_locale_tag(const QString &input, int &i, QString *result, const QString &separators)
383 *result = QString(8, Qt::Uninitialized); // worst case according to BCP47
384 QChar *pch = result->data();
385 const QChar *uc = input.data() + i;
386 const int l = input.length();
388 for (; i < l && size < 8; ++i, ++size) {
389 if (separators.contains(*uc))
391 if (! ((uc->unicode() >= 'a' && uc->unicode() <= 'z') ||
392 (uc->unicode() >= 'A' && uc->unicode() <= 'Z') ||
393 (uc->unicode() >= '0' && uc->unicode() <= '9')) ) // latin only
397 result->truncate(size);
401 bool qt_splitLocaleName(const QString &name, QString &lang, QString &script, QString &cntry)
403 const int length = name.length();
405 lang = script = cntry = QString();
407 const QString separators = QStringLiteral("_-.@");
408 enum ParserState { NoState, LangState, ScriptState, CountryState };
409 ParserState state = LangState;
410 for (int i = 0; i < length && state != NoState; ) {
412 if (!parse_locale_tag(name, i, &value, separators) ||value.isEmpty())
414 QChar sep = i < length ? name.at(i) : QChar();
417 if (!sep.isNull() && !separators.contains(sep)) {
423 // just language was specified
430 QString scripts = QString::fromLatin1((const char *)script_code_list, sizeof(script_code_list));
431 if (value.length() == 4 && scripts.indexOf(value) % 4 == 0) {
432 // script name is always 4 characters
434 state = CountryState;
436 // it wasn't a script, maybe it is a country then?
448 qWarning("QLocale: This should never happen");
453 return lang.length() == 2 || lang.length() == 3;
456 void QLocalePrivate::getLangAndCountry(const QString &name, QLocale::Language &lang,
457 QLocale::Script &script, QLocale::Country &cntry)
460 script = QLocale::AnyScript;
461 cntry = QLocale::AnyCountry;
466 if (!qt_splitLocaleName(name, lang_code, script_code, cntry_code))
469 lang = QLocalePrivate::codeToLanguage(lang_code);
470 if (lang == QLocale::C)
472 script = QLocalePrivate::codeToScript(script_code);
473 cntry = QLocalePrivate::codeToCountry(cntry_code);
476 static const QLocaleData *findLocaleData(const QString &name)
478 QLocale::Language lang;
479 QLocale::Script script;
480 QLocale::Country cntry;
481 QLocalePrivate::getLangAndCountry(name, lang, script, cntry);
483 return QLocaleData::findLocaleData(lang, script, cntry);
486 QString qt_readEscapedFormatString(const QString &format, int *idx)
490 Q_ASSERT(format.at(i) == QLatin1Char('\''));
492 if (i == format.size())
494 if (format.at(i).unicode() == '\'') { // "''" outside of a quoted stirng
496 return QLatin1String("'");
501 while (i < format.size()) {
502 if (format.at(i).unicode() == '\'') {
503 if (i + 1 < format.size() && format.at(i + 1).unicode() == '\'') {
504 // "''" inside of a quoted string
505 result.append(QLatin1Char('\''));
511 result.append(format.at(i++));
514 if (i < format.size())
520 int qt_repeatCount(const QString &s, int i)
524 while (j < s.size() && s.at(j) == c)
529 static const QLocaleData *default_data = 0;
530 static uint default_number_options = 0;
532 #ifndef QT_NO_SYSTEMLOCALE
535 /******************************************************************************
536 ** Default system locale behavior
540 Constructs a QSystemLocale object. The constructor will automatically
541 install this object as the system locale and remove any earlier installed
544 QSystemLocale::QSystemLocale()
546 delete _systemLocale;
547 _systemLocale = this;
550 system_data->m_language_id = 0;
556 QSystemLocale::QSystemLocale(bool)
562 QSystemLocale::~QSystemLocale()
564 if (_systemLocale == this) {
568 system_data->m_language_id = 0;
572 static const QSystemLocale *systemLocale()
575 return _systemLocale;
576 return QSystemLocale_globalSystemLocale();
579 void QLocalePrivate::updateSystemPrivate()
581 const QSystemLocale *sys_locale = systemLocale();
583 system_data = globalLocaleData();
585 // tell the object that the system locale has changed.
586 sys_locale->query(QSystemLocale::LocaleChanged, QVariant());
588 *system_data = *sys_locale->fallbackUiLocale().d->m_data;
590 QVariant res = sys_locale->query(QSystemLocale::LanguageId, QVariant());
592 system_data->m_language_id = res.toInt();
593 system_data->m_script_id = QLocale::AnyScript; // default for compatibility
595 res = sys_locale->query(QSystemLocale::CountryId, QVariant());
597 system_data->m_country_id = res.toInt();
598 system_data->m_script_id = QLocale::AnyScript; // default for compatibility
600 res = sys_locale->query(QSystemLocale::ScriptId, QVariant());
602 system_data->m_script_id = res.toInt();
604 res = sys_locale->query(QSystemLocale::DecimalPoint, QVariant());
606 system_data->m_decimal = res.toString().at(0).unicode();
608 res = sys_locale->query(QSystemLocale::GroupSeparator, QVariant());
610 system_data->m_group = res.toString().at(0).unicode();
612 res = sys_locale->query(QSystemLocale::ZeroDigit, QVariant());
614 system_data->m_zero = res.toString().at(0).unicode();
616 res = sys_locale->query(QSystemLocale::NegativeSign, QVariant());
618 system_data->m_minus = res.toString().at(0).unicode();
620 res = sys_locale->query(QSystemLocale::PositiveSign, QVariant());
622 system_data->m_plus = res.toString().at(0).unicode();
626 static const QLocaleData *systemData()
628 #ifndef QT_NO_SYSTEMLOCALE
629 // copy over the information from the fallback locale and modify
630 if (!system_data || system_data->m_language_id == 0)
631 QLocalePrivate::updateSystemPrivate();
639 static const QLocaleData *defaultData()
642 default_data = systemData();
646 static QString getLocaleListData(const ushort *data, int size, int index)
648 static const ushort separator = ';';
649 while (index && size > 0) {
650 while (*data != separator)
656 const ushort *end = data;
657 while (size > 0 && *end != separator)
661 return QString::fromRawData(reinterpret_cast<const QChar*>(data), end-data);
664 static inline QString getLocaleData(const ushort *data, int size)
666 return size ? QString::fromRawData(reinterpret_cast<const QChar*>(data), size) : QString();
670 #ifndef QT_NO_DATASTREAM
671 QDataStream &operator<<(QDataStream &ds, const QLocale &l)
677 QDataStream &operator>>(QDataStream &ds, QLocale &l)
684 #endif // QT_NO_DATASTREAM
687 static const int locale_data_size = sizeof(locale_data)/sizeof(QLocaleData) - 1;
689 const QLocaleData *QLocalePrivate::dataPointerForIndex(quint16 index)
691 #ifndef QT_NO_SYSTEMLOCALE
692 Q_ASSERT(index <= locale_data_size);
693 if (index == locale_data_size)
696 Q_ASSERT(index < locale_data_size);
699 return &locale_data[index];
702 static quint16 localeDataIndex(const QLocaleData *p)
704 #ifndef QT_NO_SYSTEMLOCALE
705 Q_ASSERT((p >= locale_data && p - locale_data < locale_data_size)
706 || (p != 0 && p == system_data));
707 quint16 index = p == system_data ? locale_data_size : p - locale_data;
709 Q_ASSERT(p >= locale_data && p - locale_data < locale_data_size);
710 quint16 index = p - locale_data;
719 QLocale::QLocale(QLocalePrivate &dd)
725 Constructs a QLocale object with the specified \a name,
727 "language[_script][_country][.codeset][@modifier]" or "C", where:
730 \li language is a lowercase, two-letter, ISO 639 language code (also some three-letter codes),
731 \li script is a titlecase, four-letter, ISO 15924 script code,
732 \li country is an uppercase, two-letter, ISO 3166 country code (also "419" as defined by United Nations),
733 \li and codeset and modifier are ignored.
736 The separator can be either underscore or a minus sign.
738 If the string violates the locale format, or language is not
739 a valid ISO 369 code, the "C" locale is used instead. If country
740 is not present, or is not a valid ISO 3166 code, the most
741 appropriate country is chosen for the specified language.
743 The language, script and country codes are converted to their respective
744 \c Language, \c Script and \c Country enums. After this conversion is
745 performed the constructor behaves exactly like QLocale(Country, Script,
748 This constructor is much slower than QLocale(Country, Script, Language).
753 QLocale::QLocale(const QString &name)
754 : d(new QLocalePrivate(localeDataIndex(findLocaleData(name))))
759 Constructs a QLocale object initialized with the default locale. If
760 no default locale was set using setDefault(), this locale will
761 be the same as the one returned by system().
767 : d(new QLocalePrivate(localeDataIndex(defaultData()), default_number_options))
772 Constructs a QLocale object with the specified \a language and \a
776 \li If the language/country pair is found in the database, it is used.
777 \li If the language is found but the country is not, or if the country
778 is \c AnyCountry, the language is used with the most
779 appropriate available country (for example, Germany for German),
780 \li If neither the language nor the country are found, QLocale
781 defaults to the default locale (see setDefault()).
784 The language and country that are actually used can be queried
785 using language() and country().
787 \sa setDefault(), language(), country()
790 QLocale::QLocale(Language language, Country country)
792 const QLocaleData *data = QLocaleData::findLocaleData(language, QLocale::AnyScript, country);
794 int numberOptions = 0;
796 // If not found, should default to system
797 if (data->m_language_id == QLocale::C && language != QLocale::C) {
798 numberOptions = default_number_options;
799 index = localeDataIndex(defaultData());
801 index = localeDataIndex(data);
803 d = new QLocalePrivate(index, numberOptions);
809 Constructs a QLocale object with the specified \a language, \a script and
813 \li If the language/script/country is found in the database, it is used.
814 \li If both \a script is AnyScript and \a country is AnyCountry, the
815 language is used with the most appropriate available script and country
816 (for example, Germany for German),
817 \li If either \a script is AnyScript or \a country is AnyCountry, the
818 language is used with the first locale that matches the given \a script
820 \li If neither the language nor the country are found, QLocale
821 defaults to the default locale (see setDefault()).
824 The language, script and country that are actually used can be queried
825 using language(), script() and country().
827 \sa setDefault(), language(), script(), country()
830 QLocale::QLocale(Language language, Script script, Country country)
832 const QLocaleData *data = QLocaleData::findLocaleData(language, script, country);
834 int numberOptions = 0;
836 // If not found, should default to system
837 if (data->m_language_id == QLocale::C && language != QLocale::C) {
838 numberOptions = default_number_options;
839 index = localeDataIndex(defaultData());
841 index = localeDataIndex(data);
843 d = new QLocalePrivate(index, numberOptions);
847 Constructs a QLocale object as a copy of \a other.
850 QLocale::QLocale(const QLocale &other)
864 Assigns \a other to this QLocale object and returns a reference
865 to this QLocale object.
868 QLocale &QLocale::operator=(const QLocale &other)
874 bool QLocale::operator==(const QLocale &other) const
876 return d->m_data == other.d->m_data && d->m_numberOptions == other.d->m_numberOptions;
879 bool QLocale::operator!=(const QLocale &other) const
881 return d->m_data != other.d->m_data || d->m_numberOptions != other.d->m_numberOptions;
887 Sets the \a options related to number conversions for this
890 void QLocale::setNumberOptions(NumberOptions options)
892 d->m_numberOptions = options;
898 Returns the options related to number conversions for this
901 By default, no options are set for the standard locales.
903 QLocale::NumberOptions QLocale::numberOptions() const
905 return static_cast<NumberOption>(d->m_numberOptions);
911 Returns \a str quoted according to the current locale using the given
914 QString QLocale::quoteString(const QString &str, QuotationStyle style) const
916 return quoteString(&str, style);
924 QString QLocale::quoteString(const QStringRef &str, QuotationStyle style) const
926 #ifndef QT_NO_SYSTEMLOCALE
927 if (d->m_data == systemData()) {
929 if (style == QLocale::AlternateQuotation)
930 res = systemLocale()->query(QSystemLocale::StringToAlternateQuotation, QVariant::fromValue(str));
931 if (res.isNull() || style == QLocale::StandardQuotation)
932 res = systemLocale()->query(QSystemLocale::StringToStandardQuotation, QVariant::fromValue(str));
934 return res.toString();
938 if (style == QLocale::StandardQuotation)
939 return QChar(d->m_data->m_quotation_start) % str % QChar(d->m_data->m_quotation_end);
941 return QChar(d->m_data->m_alternate_quotation_start) % str % QChar(d->m_data->m_alternate_quotation_end);
947 Returns a string that represents a join of a given \a list of strings with
948 a separator defined by the locale.
950 QString QLocale::createSeparatedList(const QStringList &list) const
952 #ifndef QT_NO_SYSTEMLOCALE
953 if (d->m_data == systemData()) {
955 res = systemLocale()->query(QSystemLocale::ListToSeparatedString, QVariant::fromValue(list));
958 return res.toString();
962 const int size = list.size();
965 } else if (size == 2) {
966 QString format = getLocaleData(list_pattern_part_data + d->m_data->m_list_pattern_part_two_idx, d->m_data->m_list_pattern_part_two_size);
967 return format.arg(list.at(0), list.at(1));
968 } else if (size > 2) {
969 QString formatStart = getLocaleData(list_pattern_part_data + d->m_data->m_list_pattern_part_start_idx, d->m_data->m_list_pattern_part_start_size);
970 QString formatMid = getLocaleData(list_pattern_part_data + d->m_data->m_list_pattern_part_mid_idx, d->m_data->m_list_pattern_part_mid_size);
971 QString formatEnd = getLocaleData(list_pattern_part_data + d->m_data->m_list_pattern_part_end_idx, d->m_data->m_list_pattern_part_end_size);
972 QString result = formatStart.arg(list.at(0), list.at(1));
973 for (int i = 2; i < size - 1; ++i)
974 result = formatMid.arg(result, list.at(i));
975 result = formatEnd.arg(result, list.at(size - 1));
985 Sets the global default locale to \a locale. These
986 values are used when a QLocale object is constructed with
987 no arguments. If this function is not called, the system's
990 \warning In a multithreaded application, the default locale
991 should be set at application startup, before any non-GUI threads
997 void QLocale::setDefault(const QLocale &locale)
999 default_data = locale.d->m_data;
1000 default_number_options = locale.numberOptions();
1004 Returns the language of this locale.
1006 \sa script(), country(), languageToString(), bcp47Name()
1008 QLocale::Language QLocale::language() const
1010 return Language(d->languageId());
1016 Returns the script of this locale.
1018 \sa language(), country(), languageToString(), scriptToString(), bcp47Name()
1020 QLocale::Script QLocale::script() const
1022 return Script(d->m_data->m_script_id);
1026 Returns the country of this locale.
1028 \sa language(), script(), countryToString(), bcp47Name()
1030 QLocale::Country QLocale::country() const
1032 return Country(d->countryId());
1036 Returns the language and country of this locale as a
1037 string of the form "language_country", where
1038 language is a lowercase, two-letter ISO 639 language code,
1039 and country is an uppercase, two- or three-letter ISO 3166 country code.
1041 Note that even if QLocale object was constructed with an explicit script,
1042 name() will not contain it for compatibility reasons. Use bcp47Name() instead
1043 if you need a full locale name.
1045 \sa QLocale(), language(), script(), country(), bcp47Name()
1048 QString QLocale::name() const
1050 Language l = language();
1052 QString result = d->languageCode();
1057 Country c = country();
1058 if (c == AnyCountry)
1061 result.append(QLatin1Char('_'));
1062 result.append(d->countryCode());
1070 Returns the dash-separated language, script and country (and possibly other BCP47 fields)
1071 of this locale as a string.
1073 Unlike the uiLanguages() the returned value of the bcp47Name() represents
1074 the locale name of the QLocale data but not the language the user-interface
1077 This function tries to conform the locale name to BCP47.
1079 \sa language(), country(), script(), uiLanguages()
1081 QString QLocale::bcp47Name() const
1083 return d->bcp47Name();
1087 Returns a QString containing the name of \a language.
1089 \sa countryToString(), scriptToString(), bcp47Name()
1092 QString QLocale::languageToString(Language language)
1094 if (uint(language) > uint(QLocale::LastLanguage))
1095 return QLatin1String("Unknown");
1096 return QLatin1String(language_name_list + language_name_index[language]);
1100 Returns a QString containing the name of \a country.
1102 \sa languageToString(), scriptToString(), country(), bcp47Name()
1105 QString QLocale::countryToString(Country country)
1107 if (uint(country) > uint(QLocale::LastCountry))
1108 return QLatin1String("Unknown");
1109 return QLatin1String(country_name_list + country_name_index[country]);
1115 Returns a QString containing the name of \a script.
1117 \sa languageToString(), countryToString(), script(), bcp47Name()
1119 QString QLocale::scriptToString(QLocale::Script script)
1121 if (uint(script) > uint(QLocale::LastScript))
1122 return QLatin1String("Unknown");
1123 return QLatin1String(script_name_list + script_name_index[script]);
1127 Returns the short int represented by the localized string \a s.
1129 If the conversion fails the function returns 0.
1131 If \a ok is not 0, failure is reported by setting *ok to false, and
1132 success by setting *ok to true.
1134 This function ignores leading and trailing whitespace.
1136 \sa toUShort(), toString()
1139 short QLocale::toShort(const QString &s, bool *ok) const
1141 qlonglong i = toLongLong(s, ok);
1142 if (i < SHRT_MIN || i > SHRT_MAX) {
1151 Returns the unsigned short int represented by the localized string \a s.
1153 If the conversion fails the function returns 0.
1155 If \a ok is not 0, failure is reported by setting *ok to false, and
1156 success by setting *ok to true.
1158 This function ignores leading and trailing whitespace.
1160 \sa toShort(), toString()
1163 ushort QLocale::toUShort(const QString &s, bool *ok) const
1165 qulonglong i = toULongLong(s, ok);
1166 if (i > USHRT_MAX) {
1175 Returns the int represented by the localized string \a s.
1177 If the conversion fails the function returns 0.
1179 If \a ok is not 0, failure is reported by setting *ok to false, and
1180 success by setting *ok to true.
1182 This function ignores leading and trailing whitespace.
1184 \sa toUInt(), toString()
1187 int QLocale::toInt(const QString &s, bool *ok) const
1189 qlonglong i = toLongLong(s, ok);
1190 if (i < INT_MIN || i > INT_MAX) {
1199 Returns the unsigned int represented by the localized string \a s.
1201 If the conversion fails the function returns 0.
1203 If \a ok is not 0, failure is reported by setting *ok to false, and
1204 success by setting *ok to true.
1206 This function ignores leading and trailing whitespace.
1208 \sa toInt(), toString()
1211 uint QLocale::toUInt(const QString &s, bool *ok) const
1213 qulonglong i = toULongLong(s, ok);
1223 Returns the long long int represented by the localized string \a s.
1225 If the conversion fails the function returns 0.
1227 If \a ok is not 0, failure is reported by setting *ok to false, and
1228 success by setting *ok to true.
1230 This function ignores leading and trailing whitespace.
1232 \sa toInt(), toULongLong(), toDouble(), toString()
1236 qlonglong QLocale::toLongLong(const QString &s, bool *ok) const
1238 QLocalePrivate::GroupSeparatorMode mode
1239 = d->m_numberOptions & RejectGroupSeparator
1240 ? QLocalePrivate::FailOnGroupSeparators
1241 : QLocalePrivate::ParseGroupSeparators;
1243 return d->stringToLongLong(s, 10, ok, mode);
1247 Returns the unsigned long long int represented by the localized
1250 If the conversion fails the function returns 0.
1252 If \a ok is not 0, failure is reported by setting *ok to false, and
1253 success by setting *ok to true.
1255 This function ignores leading and trailing whitespace.
1257 \sa toLongLong(), toInt(), toDouble(), toString()
1260 qulonglong QLocale::toULongLong(const QString &s, bool *ok) const
1262 QLocalePrivate::GroupSeparatorMode mode
1263 = d->m_numberOptions & RejectGroupSeparator
1264 ? QLocalePrivate::FailOnGroupSeparators
1265 : QLocalePrivate::ParseGroupSeparators;
1267 return d->stringToUnsLongLong(s, 10, ok, mode);
1271 Returns the float represented by the localized string \a s, or 0.0
1272 if the conversion failed.
1274 If \a ok is not 0, reports failure by setting
1275 *ok to false and success by setting *ok to true.
1277 This function ignores leading and trailing whitespace.
1279 \sa toDouble(), toInt(), toString()
1282 #define QT_MAX_FLOAT 3.4028234663852886e+38
1284 float QLocale::toFloat(const QString &s, bool *ok) const
1287 double d = toDouble(s, &myOk);
1288 if (!myOk || d > QT_MAX_FLOAT || d < -QT_MAX_FLOAT) {
1299 Returns the double represented by the localized string \a s, or
1300 0.0 if the conversion failed.
1302 If \a ok is not 0, reports failure by setting
1303 *ok to false and success by setting *ok to true.
1305 Unlike QString::toDouble(), this function does not fall back to
1306 the "C" locale if the string cannot be interpreted in this
1309 \snippet code/src_corelib_tools_qlocale.cpp 3
1311 Notice that the last conversion returns 1234.0, because '.' is the
1312 thousands group separator in the German locale.
1314 This function ignores leading and trailing whitespace.
1316 \sa toFloat(), toInt(), toString()
1319 double QLocale::toDouble(const QString &s, bool *ok) const
1321 QLocalePrivate::GroupSeparatorMode mode
1322 = d->m_numberOptions & RejectGroupSeparator
1323 ? QLocalePrivate::FailOnGroupSeparators
1324 : QLocalePrivate::ParseGroupSeparators;
1326 return d->stringToDouble(s, ok, mode);
1330 Returns a localized string representation of \a i.
1335 QString QLocale::toString(qlonglong i) const
1337 int flags = d->m_numberOptions & OmitGroupSeparator
1339 : QLocalePrivate::ThousandsGroup;
1341 return d->longLongToString(i, -1, 10, -1, flags);
1350 QString QLocale::toString(qulonglong i) const
1352 int flags = d->m_numberOptions & OmitGroupSeparator
1354 : QLocalePrivate::ThousandsGroup;
1356 return d->unsLongLongToString(i, -1, 10, -1, flags);
1360 Returns a localized string representation of the given \a date in the
1361 specified \a format.
1362 If \a format is an empty string, an empty string is returned.
1365 QString QLocale::toString(const QDate &date, const QString &format) const
1367 return d->dateTimeToString(format, &date, 0, this);
1371 Returns a localized string representation of the given \a date according
1372 to the specified \a format.
1375 QString QLocale::toString(const QDate &date, FormatType format) const
1377 if (!date.isValid())
1380 #ifndef QT_NO_SYSTEMLOCALE
1381 if (d->m_data == systemData()) {
1382 QVariant res = systemLocale()->query(format == LongFormat
1383 ? QSystemLocale::DateToStringLong : QSystemLocale::DateToStringShort,
1386 return res.toString();
1390 QString format_str = dateFormat(format);
1391 return toString(date, format_str);
1394 static bool timeFormatContainsAP(const QString &format)
1397 while (i < format.size()) {
1398 if (format.at(i).unicode() == '\'') {
1399 qt_readEscapedFormatString(format, &i);
1403 if (format.at(i).toLower().unicode() == 'a')
1411 static QString timeZone()
1413 #if defined(Q_OS_WINCE)
1414 TIME_ZONE_INFORMATION info;
1415 DWORD res = GetTimeZoneInformation(&info);
1416 if (res == TIME_ZONE_ID_UNKNOWN)
1418 return QString::fromWCharArray(info.StandardName);
1419 #elif defined(Q_OS_WIN)
1421 # if defined(_MSC_VER) && _MSC_VER >= 1400
1422 size_t returnSize = 0;
1423 char timeZoneName[512];
1424 if (_get_tzname(&returnSize, timeZoneName, 512, 1))
1426 return QString::fromLocal8Bit(timeZoneName);
1428 return QString::fromLocal8Bit(_tzname[1]);
1430 #elif defined(Q_OS_VXWORKS)
1434 return QString::fromLocal8Bit(tzname[1]);
1439 Returns a localized string representation of the given \a time according
1440 to the specified \a format.
1441 If \a format is an empty string, an empty string is returned.
1443 QString QLocale::toString(const QTime &time, const QString &format) const
1445 return d->dateTimeToString(format, 0, &time, this);
1451 Returns a localized string representation of the given \a dateTime according
1452 to the specified \a format.
1453 If \a format is an empty string, an empty string is returned.
1456 QString QLocale::toString(const QDateTime &dateTime, const QString &format) const
1458 const QDate dt = dateTime.date();
1459 const QTime tm = dateTime.time();
1460 return d->dateTimeToString(format, &dt, &tm, this);
1466 Returns a localized string representation of the given \a dateTime according
1467 to the specified \a format.
1470 QString QLocale::toString(const QDateTime &dateTime, FormatType format) const
1472 if (!dateTime.isValid())
1475 #ifndef QT_NO_SYSTEMLOCALE
1476 if (d->m_data == systemData()) {
1477 QVariant res = systemLocale()->query(format == LongFormat
1478 ? QSystemLocale::DateTimeToStringLong
1479 : QSystemLocale::DateTimeToStringShort,
1482 return res.toString();
1486 const QString format_str = dateTimeFormat(format);
1487 return toString(dateTime, format_str);
1492 Returns a localized string representation of the given \a time in the
1493 specified \a format.
1496 QString QLocale::toString(const QTime &time, FormatType format) const
1498 if (!time.isValid())
1501 #ifndef QT_NO_SYSTEMLOCALE
1502 if (d->m_data == systemData()) {
1503 QVariant res = systemLocale()->query(format == LongFormat
1504 ? QSystemLocale::TimeToStringLong : QSystemLocale::TimeToStringShort,
1507 return res.toString();
1511 QString format_str = timeFormat(format);
1512 return toString(time, format_str);
1518 Returns the date format used for the current locale.
1520 If \a format is LongFormat the format will be a long version.
1521 Otherwise it uses a shorter version.
1523 \sa QDate::toString(), QDate::fromString()
1526 QString QLocale::dateFormat(FormatType format) const
1528 #ifndef QT_NO_SYSTEMLOCALE
1529 if (d->m_data == systemData()) {
1530 QVariant res = systemLocale()->query(format == LongFormat
1531 ? QSystemLocale::DateFormatLong : QSystemLocale::DateFormatShort,
1534 return res.toString();
1541 idx = d->m_data->m_long_date_format_idx;
1542 size = d->m_data->m_long_date_format_size;
1545 idx = d->m_data->m_short_date_format_idx;
1546 size = d->m_data->m_short_date_format_size;
1549 return getLocaleData(date_format_data + idx, size);
1555 Returns the time format used for the current locale.
1557 If \a format is LongFormat the format will be a long version.
1558 Otherwise it uses a shorter version.
1560 \sa QTime::toString(), QTime::fromString()
1563 QString QLocale::timeFormat(FormatType format) const
1565 #ifndef QT_NO_SYSTEMLOCALE
1566 if (d->m_data == systemData()) {
1567 QVariant res = systemLocale()->query(format == LongFormat
1568 ? QSystemLocale::TimeFormatLong : QSystemLocale::TimeFormatShort,
1571 return res.toString();
1578 idx = d->m_data->m_long_time_format_idx;
1579 size = d->m_data->m_long_time_format_size;
1582 idx = d->m_data->m_short_time_format_idx;
1583 size = d->m_data->m_short_time_format_size;
1586 return getLocaleData(time_format_data + idx, size);
1592 Returns the date time format used for the current locale.
1594 If \a format is ShortFormat the format will be a short version.
1595 Otherwise it uses a longer version.
1597 \sa QDateTime::toString(), QDateTime::fromString()
1600 QString QLocale::dateTimeFormat(FormatType format) const
1602 #ifndef QT_NO_SYSTEMLOCALE
1603 if (d->m_data == systemData()) {
1604 QVariant res = systemLocale()->query(format == LongFormat
1605 ? QSystemLocale::DateTimeFormatLong
1606 : QSystemLocale::DateTimeFormatShort,
1608 if (!res.isNull()) {
1609 return res.toString();
1613 return dateFormat(format) + QLatin1Char(' ') + timeFormat(format);
1619 Parses the time string given in \a string and returns the
1620 time. The format of the time string is chosen according to the
1621 \a format parameter (see timeFormat()).
1623 If the time could not be parsed, returns an invalid time.
1625 \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
1627 #ifndef QT_NO_DATESTRING
1628 QTime QLocale::toTime(const QString &string, FormatType format) const
1630 return toTime(string, timeFormat(format));
1637 Parses the date string given in \a string and returns the
1638 date. The format of the date string is chosen according to the
1639 \a format parameter (see dateFormat()).
1641 If the date could not be parsed, returns an invalid date.
1643 \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
1645 #ifndef QT_NO_DATESTRING
1646 QDate QLocale::toDate(const QString &string, FormatType format) const
1648 return toDate(string, dateFormat(format));
1655 Parses the date/time string given in \a string and returns the
1656 time. The format of the date/time string is chosen according to the
1657 \a format parameter (see dateTimeFormat()).
1659 If the string could not be parsed, returns an invalid QDateTime.
1661 \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
1664 #ifndef QT_NO_DATESTRING
1665 QDateTime QLocale::toDateTime(const QString &string, FormatType format) const
1667 return toDateTime(string, dateTimeFormat(format));
1674 Parses the time string given in \a string and returns the
1675 time. See QTime::fromString() for information on what is a valid
1678 If the time could not be parsed, returns an invalid time.
1680 \sa timeFormat(), toDate(), toDateTime(), QTime::fromString()
1682 #ifndef QT_NO_DATESTRING
1683 QTime QLocale::toTime(const QString &string, const QString &format) const
1686 #ifndef QT_BOOTSTRAPPED
1687 QDateTimeParser dt(QVariant::Time, QDateTimeParser::FromString);
1688 dt.defaultLocale = *this;
1689 if (dt.parseFormat(format))
1690 dt.fromString(string, 0, &time);
1702 Parses the date string given in \a string and returns the
1703 date. See QDate::fromString() for information on the expressions
1704 that can be used with this function.
1706 This function searches month names and the names of the days of
1707 the week in the current locale.
1709 If the date could not be parsed, returns an invalid date.
1711 \sa dateFormat(), toTime(), toDateTime(), QDate::fromString()
1713 #ifndef QT_NO_DATESTRING
1714 QDate QLocale::toDate(const QString &string, const QString &format) const
1717 #ifndef QT_BOOTSTRAPPED
1718 QDateTimeParser dt(QVariant::Date, QDateTimeParser::FromString);
1719 dt.defaultLocale = *this;
1720 if (dt.parseFormat(format))
1721 dt.fromString(string, &date, 0);
1733 Parses the date/time string given in \a string and returns the
1734 time. See QDateTime::fromString() for information on the expressions
1735 that can be used with this function.
1737 \note The month and day names used must be given in the user's local
1740 If the string could not be parsed, returns an invalid QDateTime.
1742 \sa dateTimeFormat(), toTime(), toDate(), QDateTime::fromString()
1744 #ifndef QT_NO_DATESTRING
1745 QDateTime QLocale::toDateTime(const QString &string, const QString &format) const
1747 #ifndef QT_BOOTSTRAPPED
1751 QDateTimeParser dt(QVariant::DateTime, QDateTimeParser::FromString);
1752 dt.defaultLocale = *this;
1753 if (dt.parseFormat(format) && dt.fromString(string, &date, &time))
1754 return QDateTime(date, time);
1759 return QDateTime(QDate(), QTime(-1, -1, -1));
1767 Returns the decimal point character of this locale.
1769 QChar QLocale::decimalPoint() const
1771 return d->decimal();
1777 Returns the group separator character of this locale.
1779 QChar QLocale::groupSeparator() const
1787 Returns the percent character of this locale.
1789 QChar QLocale::percent() const
1791 return d->percent();
1797 Returns the zero digit character of this locale.
1799 QChar QLocale::zeroDigit() const
1807 Returns the negative sign character of this locale.
1809 QChar QLocale::negativeSign() const
1817 Returns the positive sign character of this locale.
1819 QChar QLocale::positiveSign() const
1827 Returns the exponential character of this locale.
1829 QChar QLocale::exponential() const
1831 return d->exponential();
1834 static bool qIsUpper(char c)
1836 return c >= 'A' && c <= 'Z';
1839 static char qToLower(char c)
1841 if (c >= 'A' && c <= 'Z')
1842 return c - 'A' + 'a';
1850 \a f and \a prec have the same meaning as in QString::number(double, char, int).
1855 QString QLocale::toString(double i, char f, int prec) const
1857 QLocalePrivate::DoubleForm form = QLocalePrivate::DFDecimal;
1861 flags = QLocalePrivate::CapitalEorX;
1866 form = QLocalePrivate::DFDecimal;
1869 form = QLocalePrivate::DFExponent;
1872 form = QLocalePrivate::DFSignificantDigits;
1878 if (!(d->m_numberOptions & OmitGroupSeparator))
1879 flags |= QLocalePrivate::ThousandsGroup;
1880 return d->doubleToString(i, prec, form, -1, flags);
1884 \fn QLocale QLocale::c()
1886 Returns a QLocale object initialized to the "C" locale.
1892 Returns a QLocale object initialized to the system locale.
1894 On Windows and Mac, this locale will use the decimal/grouping characters and date/time
1895 formats specified in the system configuration panel.
1900 QLocale QLocale::system()
1902 return QLocale(*new QLocalePrivate(localeDataIndex(systemData())));
1909 Returns a list of valid locale objects that match the given \a language, \a
1910 script and \a country.
1912 Getting a list of all locales:
1913 QList<QLocale> allLocales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::AnyCountry);
1915 Getting a list of locales suitable for Russia:
1916 QList<QLocale> locales = QLocale::matchingLocales(QLocale::AnyLanguage, QLocale::AnyScript, QLocale::Russia);
1918 QList<QLocale> QLocale::matchingLocales(QLocale::Language language,
1919 QLocale::Script script,
1920 QLocale::Country country)
1922 if (uint(language) > QLocale::LastLanguage || uint(script) > QLocale::LastScript ||
1923 uint(country) > QLocale::LastCountry)
1924 return QList<QLocale>();
1926 if (language == QLocale::C)
1927 return QList<QLocale>() << QLocale(QLocale::C);
1929 QList<QLocale> result;
1930 if (language == QLocale::AnyLanguage && script == QLocale::AnyScript && country == QLocale::AnyCountry)
1931 result.reserve(locale_data_size);
1932 const QLocaleData *data = locale_data + locale_index[language];
1933 while ( (data != locale_data + locale_data_size)
1934 && (language == QLocale::AnyLanguage || data->m_language_id == uint(language))) {
1935 if ((script == QLocale::AnyScript || data->m_script_id == uint(script))
1936 && (country == QLocale::AnyCountry || data->m_country_id == uint(country))) {
1937 QLocale locale(*new QLocalePrivate(localeDataIndex(data)));
1938 result.append(locale);
1949 Returns the list of countries that have entries for \a language in Qt's locale
1950 database. If the result is an empty list, then \a language is not represented in
1951 Qt's locale database.
1953 \sa matchingLocales()
1955 QList<QLocale::Country> QLocale::countriesForLanguage(Language language)
1957 QList<Country> result;
1958 if (language == C) {
1959 result << AnyCountry;
1963 unsigned language_id = language;
1964 const QLocaleData *data = locale_data + locale_index[language_id];
1965 while (data->m_language_id == language_id) {
1966 const QLocale::Country country = static_cast<Country>(data->m_country_id);
1967 if (!result.contains(country))
1968 result.append(country);
1978 Returns the localized name of \a month, in the format specified
1981 \sa dayName(), standaloneMonthName()
1983 QString QLocale::monthName(int month, FormatType type) const
1985 if (month < 1 || month > 12)
1988 #ifndef QT_NO_SYSTEMLOCALE
1989 if (d->m_data == systemData()) {
1990 QVariant res = systemLocale()->query(type == LongFormat
1991 ? QSystemLocale::MonthNameLong : QSystemLocale::MonthNameShort,
1994 return res.toString();
2000 case QLocale::LongFormat:
2001 idx = d->m_data->m_long_month_names_idx;
2002 size = d->m_data->m_long_month_names_size;
2004 case QLocale::ShortFormat:
2005 idx = d->m_data->m_short_month_names_idx;
2006 size = d->m_data->m_short_month_names_size;
2008 case QLocale::NarrowFormat:
2009 idx = d->m_data->m_narrow_month_names_idx;
2010 size = d->m_data->m_narrow_month_names_size;
2015 return getLocaleListData(months_data + idx, size, month - 1);
2021 Returns the localized name of \a month that is used as a
2022 standalone text, in the format specified by \a type.
2024 If the locale information doesn't specify the standalone month
2025 name then return value is the same as in monthName().
2027 \sa monthName(), standaloneDayName()
2029 QString QLocale::standaloneMonthName(int month, FormatType type) const
2031 if (month < 1 || month > 12)
2034 #ifndef QT_NO_SYSTEMLOCALE
2035 if (d->m_data == systemData()) {
2036 QVariant res = systemLocale()->query(type == LongFormat
2037 ? QSystemLocale::MonthNameLong : QSystemLocale::MonthNameShort,
2040 return res.toString();
2046 case QLocale::LongFormat:
2047 idx = d->m_data->m_standalone_long_month_names_idx;
2048 size = d->m_data->m_standalone_long_month_names_size;
2050 case QLocale::ShortFormat:
2051 idx = d->m_data->m_standalone_short_month_names_idx;
2052 size = d->m_data->m_standalone_short_month_names_size;
2054 case QLocale::NarrowFormat:
2055 idx = d->m_data->m_standalone_narrow_month_names_idx;
2056 size = d->m_data->m_standalone_narrow_month_names_size;
2061 QString name = getLocaleListData(months_data + idx, size, month - 1);
2063 return monthName(month, type);
2070 Returns the localized name of the \a day (where 1 represents
2071 Monday, 2 represents Tuesday and so on), in the format specified
2074 \sa monthName(), standaloneDayName()
2076 QString QLocale::dayName(int day, FormatType type) const
2078 if (day < 1 || day > 7)
2081 #ifndef QT_NO_SYSTEMLOCALE
2082 if (d->m_data == systemData()) {
2083 QVariant res = systemLocale()->query(type == LongFormat
2084 ? QSystemLocale::DayNameLong : QSystemLocale::DayNameShort,
2087 return res.toString();
2095 case QLocale::LongFormat:
2096 idx = d->m_data->m_long_day_names_idx;
2097 size = d->m_data->m_long_day_names_size;
2099 case QLocale::ShortFormat:
2100 idx = d->m_data->m_short_day_names_idx;
2101 size = d->m_data->m_short_day_names_size;
2103 case QLocale::NarrowFormat:
2104 idx = d->m_data->m_narrow_day_names_idx;
2105 size = d->m_data->m_narrow_day_names_size;
2110 return getLocaleListData(days_data + idx, size, day);
2116 Returns the localized name of the \a day (where 1 represents
2117 Monday, 2 represents Tuesday and so on) that is used as a
2118 standalone text, in the format specified by \a type.
2120 If the locale information does not specify the standalone day
2121 name then return value is the same as in dayName().
2123 \sa dayName(), standaloneMonthName()
2125 QString QLocale::standaloneDayName(int day, FormatType type) const
2127 if (day < 1 || day > 7)
2130 #ifndef QT_NO_SYSTEMLOCALE
2131 if (d->m_data == systemData()) {
2132 QVariant res = systemLocale()->query(type == LongFormat
2133 ? QSystemLocale::DayNameLong : QSystemLocale::DayNameShort,
2136 return res.toString();
2144 case QLocale::LongFormat:
2145 idx = d->m_data->m_standalone_long_day_names_idx;
2146 size = d->m_data->m_standalone_long_day_names_size;
2148 case QLocale::ShortFormat:
2149 idx = d->m_data->m_standalone_short_day_names_idx;
2150 size = d->m_data->m_standalone_short_day_names_size;
2152 case QLocale::NarrowFormat:
2153 idx = d->m_data->m_standalone_narrow_day_names_idx;
2154 size = d->m_data->m_standalone_narrow_day_names_size;
2159 QString name = getLocaleListData(days_data + idx, size, day);
2161 return dayName(day == 0 ? 7 : day, type);
2168 Returns the first day of the week according to the current locale.
2170 Qt::DayOfWeek QLocale::firstDayOfWeek() const
2172 #ifndef QT_NO_SYSTEMLOCALE
2173 if (d->m_data == systemData()) {
2174 QVariant res = systemLocale()->query(QSystemLocale::FirstDayOfWeek, QVariant());
2176 return static_cast<Qt::DayOfWeek>(res.toUInt());
2179 return static_cast<Qt::DayOfWeek>(d->m_data->m_first_day_of_week);
2182 QLocale::MeasurementSystem QLocalePrivate::measurementSystem() const
2184 for (int i = 0; i < ImperialMeasurementSystemsCount; ++i) {
2185 if (ImperialMeasurementSystems[i].languageId == m_data->m_language_id
2186 && ImperialMeasurementSystems[i].countryId == m_data->m_country_id) {
2187 return ImperialMeasurementSystems[i].system;
2190 return QLocale::MetricSystem;
2196 Returns a list of days that are considered weekdays according to the current locale.
2198 QList<Qt::DayOfWeek> QLocale::weekdays() const
2200 #ifndef QT_NO_SYSTEMLOCALE
2201 if (d->m_data == systemData()) {
2202 QVariant res = systemLocale()->query(QSystemLocale::Weekdays, QVariant());
2204 return static_cast<QList<Qt::DayOfWeek> >(res.value<QList<Qt::DayOfWeek> >());
2207 QList<Qt::DayOfWeek> weekdays;
2208 quint16 weekendStart = d->m_data->m_weekend_start;
2209 quint16 weekendEnd = d->m_data->m_weekend_end;
2210 for (int day = Qt::Monday; day <= Qt::Sunday; day++) {
2211 if ((weekendEnd >= weekendStart && (day < weekendStart || day > weekendEnd)) ||
2212 (weekendEnd < weekendStart && (day > weekendEnd && day < weekendStart)))
2213 weekdays << static_cast<Qt::DayOfWeek>(day);
2221 Returns the measurement system for the locale.
2223 QLocale::MeasurementSystem QLocale::measurementSystem() const
2225 #ifndef QT_NO_SYSTEMLOCALE
2226 if (d->m_data == systemData()) {
2227 QVariant res = systemLocale()->query(QSystemLocale::MeasurementSystem, QVariant());
2229 return MeasurementSystem(res.toInt());
2233 return d->measurementSystem();
2239 Returns the text direction of the language.
2241 Qt::LayoutDirection QLocale::textDirection() const
2243 switch (language()) {
2244 case QLocale::Arabic:
2245 case QLocale::Hebrew:
2246 case QLocale::Persian:
2247 case QLocale::Pashto:
2249 case QLocale::Syriac:
2250 case QLocale::Divehi:
2251 return Qt::RightToLeft;
2252 case QLocale::Punjabi:
2253 case QLocale::Uzbek:
2254 if (script() == QLocale::ArabicScript)
2255 return Qt::RightToLeft;
2260 return Qt::LeftToRight;
2266 Returns an uppercase copy of \a str.
2268 QString QLocale::toUpper(const QString &str) const
2272 QString result = QIcu::toUpper(d->m_localeID, str, &ok);
2275 // else fall through and use Qt's toUpper
2277 return str.toUpper();
2283 Returns a lowercase copy of \a str.
2285 QString QLocale::toLower(const QString &str) const
2289 QString result = QIcu::toLower(d->m_localeID, str, &ok);
2292 // else fall through and use Qt's toUpper
2294 return str.toLower();
2301 Returns the localized name of the "AM" suffix for times specified using
2302 the conventions of the 12-hour clock.
2306 QString QLocale::amText() const
2308 #ifndef QT_NO_SYSTEMLOCALE
2309 if (d->m_data == systemData()) {
2310 QVariant res = systemLocale()->query(QSystemLocale::AMText, QVariant());
2312 return res.toString();
2315 return getLocaleData(am_data + d->m_data->m_am_idx, d->m_data->m_am_size);
2321 Returns the localized name of the "PM" suffix for times specified using
2322 the conventions of the 12-hour clock.
2326 QString QLocale::pmText() const
2328 #ifndef QT_NO_SYSTEMLOCALE
2329 if (d->m_data == systemData()) {
2330 QVariant res = systemLocale()->query(QSystemLocale::PMText, QVariant());
2332 return res.toString();
2335 return getLocaleData(pm_data + d->m_data->m_pm_idx, d->m_data->m_pm_size);
2339 QString QLocalePrivate::dateTimeToString(const QString &format, const QDate *date, const QTime *time,
2340 const QLocale *q) const
2342 Q_ASSERT(date || time);
2343 if ((date && !date->isValid()) || (time && !time->isValid()))
2345 const bool format_am_pm = time && timeFormatContainsAP(format);
2347 enum { AM, PM } am_pm = AM;
2348 int hour12 = time ? time->hour() : -1;
2353 } else if (hour12 < 12) {
2355 } else if (hour12 == 12) {
2366 while (i < format.size()) {
2367 if (format.at(i).unicode() == '\'') {
2368 result.append(qt_readEscapedFormatString(format, &i));
2372 const QChar c = format.at(i);
2373 int repeat = qt_repeatCount(format, i);
2376 switch (c.unicode()) {
2381 else if (repeat >= 2)
2386 result.append(longLongToString(date->year(), -1, 10, 4, QLocalePrivate::ZeroPadded));
2389 result.append(longLongToString(date->year() % 100, -1, 10, 2,
2390 QLocalePrivate::ZeroPadded));
2401 repeat = qMin(repeat, 4);
2404 result.append(longLongToString(date->month()));
2407 result.append(longLongToString(date->month(), -1, 10, 2, QLocalePrivate::ZeroPadded));
2410 result.append(q->monthName(date->month(), QLocale::ShortFormat));
2413 result.append(q->monthName(date->month(), QLocale::LongFormat));
2420 repeat = qMin(repeat, 4);
2423 result.append(longLongToString(date->day()));
2426 result.append(longLongToString(date->day(), -1, 10, 2, QLocalePrivate::ZeroPadded));
2429 result.append(q->dayName(date->dayOfWeek(), QLocale::ShortFormat));
2432 result.append(q->dayName(date->dayOfWeek(), QLocale::LongFormat));
2441 if (!used && time) {
2442 switch (c.unicode()) {
2445 repeat = qMin(repeat, 2);
2446 const int hour = format_am_pm ? hour12 : time->hour();
2450 result.append(longLongToString(hour));
2453 result.append(longLongToString(hour, -1, 10, 2, QLocalePrivate::ZeroPadded));
2460 repeat = qMin(repeat, 2);
2463 result.append(longLongToString(time->hour()));
2466 result.append(longLongToString(time->hour(), -1, 10, 2, QLocalePrivate::ZeroPadded));
2473 repeat = qMin(repeat, 2);
2476 result.append(longLongToString(time->minute()));
2479 result.append(longLongToString(time->minute(), -1, 10, 2, QLocalePrivate::ZeroPadded));
2486 repeat = qMin(repeat, 2);
2489 result.append(longLongToString(time->second()));
2492 result.append(longLongToString(time->second(), -1, 10, 2, QLocalePrivate::ZeroPadded));
2499 if (i + 1 < format.length() && format.at(i + 1).unicode() == 'p') {
2504 result.append(am_pm == AM ? q->amText().toLower() : q->pmText().toLower());
2509 if (i + 1 < format.length() && format.at(i + 1).unicode() == 'P') {
2514 result.append(am_pm == AM ? q->amText().toUpper() : q->pmText().toUpper());
2526 result.append(longLongToString(time->msec()));
2529 result.append(longLongToString(time->msec(), -1, 10, 3, QLocalePrivate::ZeroPadded));
2537 result.append(timeZone());
2544 result.append(QString(repeat, c));
2552 QString QLocalePrivate::doubleToString(double d,
2556 unsigned flags) const
2558 return QLocalePrivate::doubleToString(zero(), plus(), minus(), exponential(),
2560 d, precision, form, width, flags);
2563 QString QLocalePrivate::doubleToString(const QChar _zero, const QChar plus, const QChar minus,
2564 const QChar exponential, const QChar group, const QChar decimal,
2571 if (precision == -1)
2576 bool negative = false;
2577 bool special_number = false; // nan, +/-inf
2580 // Detect special numbers (nan, +/-inf)
2582 num_str = QString::fromLatin1("inf");
2583 special_number = true;
2585 } else if (qt_is_nan(d)) {
2586 num_str = QString::fromLatin1("nan");
2587 special_number = true;
2590 // Handle normal numbers
2591 if (!special_number) {
2595 #ifdef QT_QLOCALE_USES_FCVT
2597 if (form == DFDecimal) {
2598 digits = QLatin1String(fcvt(d, precision, &decpt, &sign));
2601 if (form == DFExponent)
2603 else if (form == DFSignificantDigits && pr == 0)
2605 digits = QLatin1String(ecvt(d, pr, &decpt, &sign));
2607 // Chop trailing zeros
2608 if (digits.length() > 0) {
2609 int last_nonzero_idx = digits.length() - 1;
2610 while (last_nonzero_idx > 0
2611 && digits.unicode()[last_nonzero_idx] == QLatin1Char('0'))
2613 digits.truncate(last_nonzero_idx + 1);
2620 if (form == DFDecimal)
2625 /* This next bit is a bit quirky. In DFExponent form, the precision
2626 is the number of digits after decpt. So that would suggest using
2627 mode=3 for qdtoa. But qdtoa behaves strangely when mode=3 and
2628 precision=0. So we get around this by using mode=2 and reasoning
2629 that we want precision+1 significant digits, since the decimal
2630 point in this mode is always after the first digit. */
2632 if (form == DFExponent)
2638 digits = QLatin1String(qdtoa(d, mode, pr, &decpt, &sign, &rve, &buff));
2646 #endif // QT_QLOCALE_USES_FCVT
2648 if (_zero.unicode() != '0') {
2649 ushort z = _zero.unicode() - '0';
2650 for (int i = 0; i < digits.length(); ++i)
2651 reinterpret_cast<ushort *>(digits.data())[i] += z;
2654 bool always_show_decpt = (flags & Alternate || flags & ForcePoint);
2657 num_str = exponentForm(_zero, decimal, exponential, group, plus, minus,
2658 digits, decpt, precision, PMDecimalDigits,
2663 num_str = decimalForm(_zero, decimal, group,
2664 digits, decpt, precision, PMDecimalDigits,
2665 always_show_decpt, flags & ThousandsGroup);
2668 case DFSignificantDigits: {
2669 PrecisionMode mode = (flags & Alternate) ?
2670 PMSignificantDigits : PMChopTrailingZeros;
2672 if (decpt != digits.length() && (decpt <= -4 || decpt > precision))
2673 num_str = exponentForm(_zero, decimal, exponential, group, plus, minus,
2674 digits, decpt, precision, mode,
2677 num_str = decimalForm(_zero, decimal, group,
2678 digits, decpt, precision, mode,
2679 always_show_decpt, flags & ThousandsGroup);
2684 negative = sign != 0 && !isZero(d);
2687 // pad with zeros. LeftAdjusted overrides this flag). Also, we don't
2688 // pad special numbers
2689 if (flags & QLocalePrivate::ZeroPadded
2690 && !(flags & QLocalePrivate::LeftAdjusted)
2691 && !special_number) {
2692 int num_pad_chars = width - num_str.length();
2693 // leave space for the sign
2695 || flags & QLocalePrivate::AlwaysShowSign
2696 || flags & QLocalePrivate::BlankBeforePositive)
2699 for (int i = 0; i < num_pad_chars; ++i)
2700 num_str.prepend(_zero);
2705 num_str.prepend(minus);
2706 else if (flags & QLocalePrivate::AlwaysShowSign)
2707 num_str.prepend(plus);
2708 else if (flags & QLocalePrivate::BlankBeforePositive)
2709 num_str.prepend(QLatin1Char(' '));
2711 if (flags & QLocalePrivate::CapitalEorX)
2712 num_str = num_str.toUpper();
2717 QString QLocalePrivate::longLongToString(qlonglong l, int precision,
2718 int base, int width,
2719 unsigned flags) const
2721 return QLocalePrivate::longLongToString(zero(), group(), plus(), minus(),
2722 l, precision, base, width, flags);
2725 QString QLocalePrivate::longLongToString(const QChar zero, const QChar group,
2726 const QChar plus, const QChar minus,
2727 qlonglong l, int precision,
2728 int base, int width,
2731 bool precision_not_specified = false;
2732 if (precision == -1) {
2733 precision_not_specified = true;
2737 bool negative = l < 0;
2739 // these are not supported by sprintf for octal and hex
2740 flags &= ~AlwaysShowSign;
2741 flags &= ~BlankBeforePositive;
2742 negative = false; // neither are negative numbers
2747 num_str = qlltoa(l, base, zero);
2749 num_str = qulltoa(l, base, zero);
2751 uint cnt_thousand_sep = 0;
2752 if (flags & ThousandsGroup && base == 10) {
2753 for (int i = num_str.length() - 3; i > 0; i -= 3) {
2754 num_str.insert(i, group);
2759 for (int i = num_str.length()/* - cnt_thousand_sep*/; i < precision; ++i)
2760 num_str.prepend(base == 10 ? zero : QChar::fromLatin1('0'));
2762 if ((flags & Alternate || flags & ShowBase)
2764 && (num_str.isEmpty() || num_str[0].unicode() != QLatin1Char('0')))
2765 num_str.prepend(QLatin1Char('0'));
2767 // LeftAdjusted overrides this flag ZeroPadded. sprintf only padds
2768 // when precision is not specified in the format string
2769 bool zero_padded = flags & ZeroPadded
2770 && !(flags & LeftAdjusted)
2771 && precision_not_specified;
2774 int num_pad_chars = width - num_str.length();
2776 // leave space for the sign
2778 || flags & AlwaysShowSign
2779 || flags & BlankBeforePositive)
2782 // leave space for optional '0x' in hex form
2783 if (base == 16 && (flags & Alternate || flags & ShowBase))
2785 // leave space for optional '0b' in binary form
2786 else if (base == 2 && (flags & Alternate || flags & ShowBase))
2789 for (int i = 0; i < num_pad_chars; ++i)
2790 num_str.prepend(base == 10 ? zero : QChar::fromLatin1('0'));
2793 if (flags & CapitalEorX)
2794 num_str = num_str.toUpper();
2796 if (base == 16 && (flags & Alternate || flags & ShowBase))
2797 num_str.prepend(QLatin1String(flags & UppercaseBase ? "0X" : "0x"));
2798 if (base == 2 && (flags & Alternate || flags & ShowBase))
2799 num_str.prepend(QLatin1String(flags & UppercaseBase ? "0B" : "0b"));
2803 num_str.prepend(minus);
2804 else if (flags & AlwaysShowSign)
2805 num_str.prepend(plus);
2806 else if (flags & BlankBeforePositive)
2807 num_str.prepend(QLatin1Char(' '));
2812 QString QLocalePrivate::unsLongLongToString(qulonglong l, int precision,
2813 int base, int width,
2814 unsigned flags) const
2816 return QLocalePrivate::unsLongLongToString(zero(), group(), plus(),
2817 l, precision, base, width, flags);
2820 QString QLocalePrivate::unsLongLongToString(const QChar zero, const QChar group,
2822 qulonglong l, int precision,
2823 int base, int width,
2826 bool precision_not_specified = false;
2827 if (precision == -1) {
2828 precision_not_specified = true;
2832 QString num_str = qulltoa(l, base, zero);
2834 uint cnt_thousand_sep = 0;
2835 if (flags & ThousandsGroup && base == 10) {
2836 for (int i = num_str.length() - 3; i > 0; i -=3) {
2837 num_str.insert(i, group);
2842 for (int i = num_str.length()/* - cnt_thousand_sep*/; i < precision; ++i)
2843 num_str.prepend(base == 10 ? zero : QChar::fromLatin1('0'));
2845 if ((flags & Alternate || flags & ShowBase)
2847 && (num_str.isEmpty() || num_str[0].unicode() != QLatin1Char('0')))
2848 num_str.prepend(QLatin1Char('0'));
2850 // LeftAdjusted overrides this flag ZeroPadded. sprintf only padds
2851 // when precision is not specified in the format string
2852 bool zero_padded = flags & ZeroPadded
2853 && !(flags & LeftAdjusted)
2854 && precision_not_specified;
2857 int num_pad_chars = width - num_str.length();
2859 // leave space for optional '0x' in hex form
2860 if (base == 16 && flags & Alternate)
2862 // leave space for optional '0b' in binary form
2863 else if (base == 2 && flags & Alternate)
2866 for (int i = 0; i < num_pad_chars; ++i)
2867 num_str.prepend(base == 10 ? zero : QChar::fromLatin1('0'));
2870 if (flags & CapitalEorX)
2871 num_str = num_str.toUpper();
2873 if (base == 16 && (flags & Alternate || flags & ShowBase))
2874 num_str.prepend(QLatin1String(flags & UppercaseBase ? "0X" : "0x"));
2875 else if (base == 2 && (flags & Alternate || flags & ShowBase))
2876 num_str.prepend(QLatin1String(flags & UppercaseBase ? "0B" : "0b"));
2879 if (flags & AlwaysShowSign)
2880 num_str.prepend(plus);
2881 else if (flags & BlankBeforePositive)
2882 num_str.prepend(QLatin1Char(' '));
2888 Converts a number in locale to its representation in the C locale.
2889 Only has to guarantee that a string that is a correct representation of
2890 a number will be converted. If junk is passed in, junk will be passed
2891 out and the error will be detected during the actual conversion to a
2892 number. We can't detect junk here, since we don't even know the base
2895 bool QLocalePrivate::numberToCLocale(const QString &num,
2896 GroupSeparatorMode group_sep_mode,
2897 CharBuff *result) const
2899 const QChar *uc = num.unicode();
2900 int l = num.length();
2904 while (idx < l && uc[idx].isSpace())
2910 const QChar in = uc[idx];
2912 char out = digitToCLocale(in);
2916 else if (in == percent())
2918 // for handling base-x numbers
2919 else if (in.unicode() >= 'A' && in.unicode() <= 'Z')
2920 out = in.toLower().toLatin1();
2921 else if (in.unicode() >= 'a' && in.unicode() <= 'z')
2922 out = in.toLatin1();
2927 result->append(out);
2932 // Check trailing whitespace
2933 for (; idx < l; ++idx) {
2934 if (!uc[idx].isSpace())
2938 result->append('\0');
2941 if (group_sep_mode == ParseGroupSeparators
2942 && !removeGroupSeparators(result))
2949 bool QLocalePrivate::validateChars(const QString &str, NumberMode numMode, QByteArray *buff,
2950 int decDigits) const
2953 buff->reserve(str.length());
2955 const bool scientific = numMode == DoubleScientificMode;
2956 bool lastWasE = false;
2957 bool lastWasDigit = false;
2959 int decPointCnt = 0;
2961 int decDigitCnt = 0;
2963 for (int i = 0; i < str.length(); ++i) {
2964 char c = digitToCLocale(str.at(i));
2966 if (c >= '0' && c <= '9') {
2967 if (numMode != IntegerMode) {
2968 // If a double has too many digits after decpt, it shall be Invalid.
2969 if (dec && decDigits != -1 && decDigits < ++decDigitCnt)
2972 lastWasDigit = true;
2976 if (numMode == IntegerMode) {
2977 // If an integer has a decimal point, it shall be Invalid.
2980 // If a double has more than one decimal point, it shall be Invalid.
2981 if (++decPointCnt > 1)
2984 // If a double with no decimal digits has a decimal point, it shall be
2988 #endif // On second thoughts, it shall be Valid.
2997 // If a scientific has a sign that's not at the beginning or after
2998 // an 'e', it shall be Invalid.
2999 if (i != 0 && !lastWasE)
3002 // If a non-scientific has a sign that's not at the beginning,
3003 // it shall be Invalid.
3010 //it can only be placed after a digit which is before the decimal point
3011 if (!lastWasDigit || decPointCnt > 0)
3017 // If a scientific has more than one 'e', it shall be Invalid.
3022 // If a non-scientific has an 'e', it shall be Invalid.
3028 // If it's not a valid digit, it shall be Invalid.
3031 lastWasDigit = false;
3034 lastWasE = c == 'e';
3042 double QLocalePrivate::stringToDouble(const QString &number, bool *ok,
3043 GroupSeparatorMode group_sep_mode) const
3046 if (!numberToCLocale(group().unicode() == 0xa0 ? number.trimmed() : number,
3047 group_sep_mode, &buff)) {
3052 return bytearrayToDouble(buff.constData(), ok);
3055 qlonglong QLocalePrivate::stringToLongLong(const QString &number, int base,
3056 bool *ok, GroupSeparatorMode group_sep_mode) const
3059 if (!numberToCLocale(group().unicode() == 0xa0 ? number.trimmed() : number,
3060 group_sep_mode, &buff)) {
3066 return bytearrayToLongLong(buff.constData(), base, ok);
3069 qulonglong QLocalePrivate::stringToUnsLongLong(const QString &number, int base,
3070 bool *ok, GroupSeparatorMode group_sep_mode) const
3073 if (!numberToCLocale(group().unicode() == 0xa0 ? number.trimmed() : number,
3074 group_sep_mode, &buff)) {
3080 return bytearrayToUnsLongLong(buff.constData(), base, ok);
3084 double QLocalePrivate::bytearrayToDouble(const char *num, bool *ok, bool *overflow)
3097 if (qstrcmp(num, "nan") == 0)
3100 if (qstrcmp(num, "+inf") == 0 || qstrcmp(num, "inf") == 0)
3103 if (qstrcmp(num, "-inf") == 0)
3108 double d = qstrtod(num, &endptr, &_ok);
3111 // the only way strtod can fail with *endptr != '\0' on a non-empty
3112 // input string is overflow
3116 *overflow = *endptr != '\0';
3120 if (*endptr != '\0') {
3121 // we stopped at a non-digit character after converting some digits
3136 qlonglong QLocalePrivate::bytearrayToLongLong(const char *num, int base, bool *ok, bool *overflow)
3149 qlonglong l = qstrtoll(num, &endptr, base, &_ok);
3154 if (overflow != 0) {
3155 // the only way qstrtoll can fail with *endptr != '\0' on a non-empty
3156 // input string is overflow
3157 *overflow = *endptr != '\0';
3162 if (*endptr != '\0') {
3163 // we stopped at a non-digit character after converting some digits
3178 qulonglong QLocalePrivate::bytearrayToUnsLongLong(const char *num, int base, bool *ok)
3182 qulonglong l = qstrtoull(num, &endptr, base, &_ok);
3184 if (!_ok || *endptr != '\0') {
3198 \enum QLocale::CurrencySymbolFormat
3200 Specifies the format of the currency symbol.
3202 \value CurrencyIsoCode a ISO-4217 code of the currency.
3203 \value CurrencySymbol a currency symbol.
3204 \value CurrencyDisplayName a user readable name of the currency.
3209 Returns a currency symbol according to the \a format.
3211 QString QLocale::currencySymbol(QLocale::CurrencySymbolFormat format) const
3213 #ifndef QT_NO_SYSTEMLOCALE
3214 if (d->m_data == systemData()) {
3215 QVariant res = systemLocale()->query(QSystemLocale::CurrencySymbol, format);
3217 return res.toString();
3222 case CurrencySymbol:
3223 idx = d->m_data->m_currency_symbol_idx;
3224 size = d->m_data->m_currency_symbol_size;
3225 return getLocaleData(currency_symbol_data + idx, size);
3226 case CurrencyDisplayName:
3227 idx = d->m_data->m_currency_display_name_idx;
3228 size = d->m_data->m_currency_display_name_size;
3229 return getLocaleListData(currency_display_name_data + idx, size, 0);
3230 case CurrencyIsoCode: {
3232 const QLocaleData *data = this->d->m_data;
3233 for (; len < 3; ++len)
3234 if (!data->m_currency_iso_code[len])
3236 return len ? QString::fromLatin1(data->m_currency_iso_code, len) : QString();
3245 Returns a localized string representation of \a value as a currency.
3246 If the \a symbol is provided it is used instead of the default currency symbol.
3248 \sa currencySymbol()
3250 QString QLocale::toCurrencyString(qlonglong value, const QString &symbol) const
3252 #ifndef QT_NO_SYSTEMLOCALE
3253 if (d->m_data == systemData()) {
3254 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
3255 QVariant res = systemLocale()->query(QSystemLocale::CurrencyToString, QVariant::fromValue(arg));
3257 return res.toString();
3260 const QLocalePrivate *d = this->d;
3261 quint8 idx = d->m_data->m_currency_format_idx;
3262 quint8 size = d->m_data->m_currency_format_size;
3263 if (d->m_data->m_currency_negative_format_size && value < 0) {
3264 idx = d->m_data->m_currency_negative_format_idx;
3265 size = d->m_data->m_currency_negative_format_size;
3268 QString str = toString(value);
3269 QString sym = symbol.isNull() ? currencySymbol() : symbol;
3271 sym = currencySymbol(QLocale::CurrencyIsoCode);
3272 QString format = getLocaleData(currency_format_data + idx, size);
3273 return format.arg(str, sym);
3280 QString QLocale::toCurrencyString(qulonglong value, const QString &symbol) const
3282 #ifndef QT_NO_SYSTEMLOCALE
3283 if (d->m_data == systemData()) {
3284 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
3285 QVariant res = systemLocale()->query(QSystemLocale::CurrencyToString, QVariant::fromValue(arg));
3287 return res.toString();
3290 const QLocaleData *data = this->d->m_data;
3291 quint8 idx = data->m_currency_format_idx;
3292 quint8 size = data->m_currency_format_size;
3293 QString str = toString(value);
3294 QString sym = symbol.isNull() ? currencySymbol() : symbol;
3296 sym = currencySymbol(QLocale::CurrencyIsoCode);
3297 QString format = getLocaleData(currency_format_data + idx, size);
3298 return format.arg(str, sym);
3305 QString QLocale::toCurrencyString(double value, const QString &symbol) const
3307 #ifndef QT_NO_SYSTEMLOCALE
3308 if (d->m_data == systemData()) {
3309 QSystemLocale::CurrencyToStringArgument arg(value, symbol);
3310 QVariant res = systemLocale()->query(QSystemLocale::CurrencyToString, QVariant::fromValue(arg));
3312 return res.toString();
3315 const QLocaleData *data = this->d->m_data;
3316 quint8 idx = data->m_currency_format_idx;
3317 quint8 size = data->m_currency_format_size;
3318 if (data->m_currency_negative_format_size && value < 0) {
3319 idx = data->m_currency_negative_format_idx;
3320 size = data->m_currency_negative_format_size;
3323 QString str = toString(value, 'f', d->m_data->m_currency_digits);
3324 QString sym = symbol.isNull() ? currencySymbol() : symbol;
3326 sym = currencySymbol(QLocale::CurrencyIsoCode);
3327 QString format = getLocaleData(currency_format_data + idx, size);
3328 return format.arg(str, sym);
3334 Returns an ordered list of locale names for translation purposes in
3335 preference order (like "en", "en-US", "en-Latn-US").
3337 The return value represents locale names that the user expects to see the
3340 Most like you do not need to use this function directly, but just pass the
3341 QLocale object to the QTranslator::load() function.
3343 The first item in the list is the most preferred one.
3345 \sa QTranslator, bcp47Name()
3347 QStringList QLocale::uiLanguages() const
3349 #ifndef QT_NO_SYSTEMLOCALE
3350 if (d->m_data == systemData()) {
3351 QVariant res = systemLocale()->query(QSystemLocale::UILanguages, QVariant());
3352 if (!res.isNull()) {
3353 QStringList result = res.toStringList();
3354 if (!result.isEmpty())
3359 QLocaleId id = QLocaleId::fromIds(d->m_data->m_language_id, d->m_data->m_script_id, d->m_data->m_country_id);
3360 const QLocaleId max = id.withLikelySubtagsAdded();
3361 const QLocaleId min = max.withLikelySubtagsRemoved();
3363 QStringList uiLanguages;
3364 uiLanguages.append(min.bcp47Name());
3367 if (id != min && id.withLikelySubtagsAdded() == max)
3368 uiLanguages.append(id.bcp47Name());
3370 if (max != min && max != id)
3371 uiLanguages.append(max.bcp47Name());
3378 Returns a native name of the language for the locale. For example
3379 "Schwiizertüütsch" for Swiss-German locale.
3381 \sa nativeCountryName(), languageToString()
3383 QString QLocale::nativeLanguageName() const
3385 #ifndef QT_NO_SYSTEMLOCALE
3386 if (d->m_data == systemData()) {
3387 QVariant res = systemLocale()->query(QSystemLocale::NativeLanguageName, QVariant());
3389 return res.toString();
3392 return getLocaleData(endonyms_data + d->m_data->m_language_endonym_idx, d->m_data->m_language_endonym_size);
3398 Returns a native name of the country for the locale. For example
3399 "España" for Spanish/Spain locale.
3401 \sa nativeLanguageName(), countryToString()
3403 QString QLocale::nativeCountryName() const
3405 #ifndef QT_NO_SYSTEMLOCALE
3406 if (d->m_data == systemData()) {
3407 QVariant res = systemLocale()->query(QSystemLocale::NativeCountryName, QVariant());
3409 return res.toString();
3412 return getLocaleData(endonyms_data + d->m_data->m_country_endonym_idx, d->m_data->m_country_endonym_size);
3415 #ifndef QT_NO_DEBUG_STREAM
3416 QDebug operator<<(QDebug dbg, const QLocale &l)
3418 dbg.nospace() << "QLocale(" << qPrintable(QLocale::languageToString(l.language()))
3419 << ", " << qPrintable(QLocale::scriptToString(l.script()))
3420 << ", " << qPrintable(QLocale::countryToString(l.country())) << ')';