Home > front end >  Qt - QString Numerical Format String (cformat), Options?
Qt - QString Numerical Format String (cformat), Options?

Time:10-05

I have user-provided format string (e.g. "%.2f") and a QVariant type that I am attempting to combine to output into a (formatted) string.

I had gone down the path of using QString::asprintf(const char *cformat, ...) to achieve this, where I would supply the appropriate converted data type, like this:

QString result_str = QString::asprintf(disp_fmt.toUtf8(),variant_type.toUInt());

This works fine for the most part, especially when I have a floating point as the input. However, if my format string in this particular integer (.toUInt()) conversion case includes decimal formatting (e.g. "%.2f"), then I get a constant result of "0.00". This caught me by surprise as I expected to instead just get ".00" tacked onto the integer, as I have seen in other languages like Perl.

What am I missing here? Also, I know asprintf() was added fairly recently and the documentation already now advises to use QTextStream or arg() instead. I don't believe this to be an option, however, for me to use this style of format string. Thanks.

CodePudding user response:

The format string is expecting a double, but you're providing an int. It works if you provide an actual double, like this:

QString result_str = QString::asprintf(disp_fmt.toUtf8(),variant_type.toDouble());

Also note, this behavior is identical to how the standard C library functions work (std::sprintf, etc).

  • Related