本页

数字 JavaScript 对象

QML Number 对象扩展了 JS Number 对象,并提供了本地化功能。

字符串 Number::toLocaleString(locale, format, precision)

将 Number 转换为适合指定locale 、指定format 和指定precision 的字符串。

有效格式为

  • f'十进制浮点数,例如 248.65
  • e'使用 e 字符的科学记数法,如 2.4865e+2
  • E'使用 E 字符的科学记数法,如 2.4865E+2
  • g'使用 e 或 f 中较短的字符
  • G'使用 E 或 f 的较短值

如果未指定精度,精度将为 2。

如果未指定格式,将使用 "f"。

如果未指定locale ,将使用默认的本地语言。

下面的示例显示了一个按德语本地语言格式化的数字:

import QtQuick 2.0

Text {
    text: "The value is: " +  Number(4742378.423).toLocaleString(Qt.locale("de_DE"))
}

您可以自定义locale 的各个字段,以严格控制输出:

let locale = Qt.locale("de_DE");
let a = Number(1000).toLocaleString(locale)); // a == 1.000,00
locale.numberOptions = Locale.OmitGroupSeparator;
let b = Number(1000).toLocaleString(locale)); // b == 1000,00

您可以直接将 toLocaleString() 应用于常量,前提是常量中包含小数,例如

123.0.toLocaleString(Qt.locale("de_DE")) // OK
123..toLocaleString(Qt.locale("de_DE"))  // OK
123.toLocaleString(Qt.locale("de_DE"))   // fails

字符串 Number::toLocaleCurrencyString(locale, symbol)

使用指定locale 的货币和约定将 Number 转换为货币。如果指定了symbol ,它将被用作货币符号。

string Number::fromLocaleString(locale, number)

使用所提供的locale 的约定对number 进行解析,返回一个 Number。

如果未提供locale ,则将使用默认语言。

例如,使用德语语言:

var german = Qt.locale("de_DE");
var d;
d = Number.fromLocaleString(german, "1234,56")   // d == 1234.56
d = Number.fromLocaleString(german, "1.234,56") // d == 1234.56
d = Number.fromLocaleString(german, "1234.56")  // throws exception
d = Number.fromLocaleString(german, "1.234")    // d == 1234.0

另请参阅 LocaleLocale::currencySymbol()。

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.