JavaScript 数字对象
QML 的 Number 对象在 JS 的 Number 对象基础上扩展了支持区域设置的功能。
string 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")) // failsstring 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另请参阅 ` Locale ` 和 `Locale::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.