通过QString的arg函数设置double类型变量的精度
Qt5源代码中的函数
Q_REQUIRED_RESULT QString arg(double a, int fieldWidth = 0, char fmt = 'g', int prec = -1, QChar fillChar = QLatin1Char(' ')) const;
/*!
\fn QString QString::arg(double a, int fieldWidth, char format, int precision, QChar fillChar) const
\overload arg()
Argument \a a is formatted according to the specified \a format and
\a precision. See \l{Argument Formats} for details.
\a fieldWidth specifies the minimum amount of space that \a a is
padded to and filled with the character \a fillChar. A positive
value produces right-aligned text; a negative value produces
left-aligned text.
\snippet code/src_corelib_tools_qstring.cpp 2
The '%' can be followed by an 'L', in which case the sequence is
replaced with a localized representation of \a a. The conversion
uses the default locale, set by QLocale::setDefault(). If no
default locale was specified, the "C" locale is used.
If \a fillChar is '0' (the number 0, ASCII 48), this function will
use the locale's zero to pad. For negative numbers, the zero padding
will probably appear before the minus sign.
\sa QLocale::toString()
*/
QString QString::arg(double a, int fieldWidth, char fmt, int prec, QChar fillChar) const
{
ArgEscapeData d = findArgEscapes(*this);
if (d.occurrences == 0) {
qWarning("QString::arg: Argument missing: %s, %g", toLocal8Bit().data(), a);
return *this;
}
unsigned flags = QLocaleData::NoFlags;
if (fillChar == QLatin1Char('0'))
flags |= QLocaleData::ZeroPadded;
if (qIsUpper(fmt))
flags |= QLocaleData::CapitalEorX;
QLocaleData::DoubleForm form = QLocaleData::DFDecimal;
switch (qToLower(fmt)) {
case 'f':
form = QLocaleData::DFDecimal;
break;
case 'e':
form = QLocaleData::DFExponent;
break;
case 'g':
form = QLocaleData::DFSignificantDigits;
break;
default:
#if defined(QT_CHECK_RANGE)
qWarning("QString::arg: Invalid format char '%c'", fmt);
#endif
break;
}
QString arg;
if (d.occurrences > d.locale_occurrences)
arg = QLocaleData::c()->doubleToString(a, prec, form, fieldWidth, flags | QLocaleData::ZeroPadExponent);
QString locale_arg;
if (d.locale_occurrences > 0) {
QLocale locale;
const QLocale::NumberOptions numberOptions = locale.numberOptions();
if (!(numberOptions & QLocale::OmitGroupSeparator))
flags |= QLocaleData::ThousandsGroup;
if (!(numberOptions & QLocale::OmitLeadingZeroInExponent))
flags |= QLocaleData::ZeroPadExponent;
if (numberOptions & QLocale::IncludeTrailingZeroesAfterDot)
flags |= QLocaleData::AddTrailingZeroes;
locale_arg = locale.d->m_data->doubleToString(a, prec, form, fieldWidth, flags);
}
return replaceArgEscapes(*this, d, fieldWidth, arg, locale_arg, fillChar);
}
源码链接: link
基本解释:
fmt 是不区分大小写的,但是只支持3个字母,g, f 和 e。
filedWidth 的含义是总共占的位置,如果filedWidth大于实际值,会用fillChar补充
prec是精度,当fmt为f时代表小数点后面的位数,当fmt为g时代表总共的位数