Formatting floating point values as strings
-
I am trying to be in complete control of how I am going to format a string containing a flotaing point value (be it float or double), in terms of width and precision.
Looking at google and Qt documentaton I see three different approaches:
- QString::asprintf : very c-oriented
- QTextString : very c++-iostream-oriented
- QString::arg() : lets say modern-languages-oriented
documentation for QString::asprintf suggests avoiding it, but rather use either one or the other of the two alternatives.
I then looked at documenation for QString::arg() , and I am very disappointed about myself for being unable to find which values are supported for the parameter format
Am I allowed to pretend that I can pass any of the 256 values a char can have, and that there are 256 different ways to format a floating values? :P
Is there ANY way that Qt Documentation can be considered as reliable and somewhat complete? How am I supposed to use Qt published documentation?Thanks in advance to anyone willing and capable of enlightnening about Qt Documentation, so far I feel totally clueless and rather helpless.
-
The QString::arg() documentation points to https://doc.qt.io/qt-6/qstring.html#floating-point-formats which then explains the possible values in https://doc.qt.io/qt-6/qlocale.html#toString-8
-
BTW, there is also QString::number() (with the same options as QString::arg()).
So far, I haven't found any library that gives you full control over formatting. I'm working on some old simulation code and floating point values are stored as ASCII with 10 characters. No library (iostreams, fmt, Qt) will fully conform too just 10 characters if specified or will use a suboptimal representation (looking at you, MSVC: adding e+003 instead of just e3 to a number unnecessarily looses a lot of precision when squeezed into 10 characters). I succinctly remember iostreams with MSVC (newer versions) and fmt for some numbers to use more than 10 characters. We now have our own functions for formatting numbers based on the output of dragonbox (https://github.com/jk-jeon/dragonbox).
-
@SimonSchroeder std::format in C++ 20 may be another option.
-
@JoeCFD said in Formatting floating point values as strings:
std::format in C++ 20 may be another option.
It is usually derived from the fmt library and thus has the same problems associated with it. I'm not sure about all the compiler, but because we are compiling on Windows, Linux, and macOS there will be at least one compiler (with its associated library) that is the same as the fmt library.
-
B BaroneAshura has marked this topic as solved on