Uploaded image for project: 'Qt'
  1. Qt
  2. QTBUG-138145

Number conversions do not round to even

XMLWordPrintable

    • Icon: Bug Bug
    • Resolution: Unresolved
    • Icon: P2: Important P2: Important
    • None
    • 6.9
    • None
    • 13
    • Foundation PM Staging

      Converting a floating-point number using QString::number, arg() etc. to a string rounds away from zero (JavaScript semantics), instead of rounding half to even (IEEE754's default, i.e. printf / std::format / std::to_chars / Python / Rust / ... semantics).

      Example:

      qDebug() << QString::number(0.25, 'f', 1);
      qDebug() << QString("%1").arg(0.25, 0, 'f', 1);
      

      prints "0.3" (twice) instead of "0.2". 0.25 is precise, and should be rounded to even to 0.2.

      Indeed:

      printf("%.1f\n", 0.25);
      std::println("{:.1f}", 0.25);
      

      prints "0.2".

      This is due to libdouble-conversion, which has JS semantics, and documents the choice:

        //   'v'. If there are two at the same distance, than the one farther away
        //   from 0 is chosen (halfway cases - ending with 5 - are rounded up).
      

      However this also means that we get inconsistent outputs between builds with and without libdouble-conversion (bootstrap; different build configurations; and complicates porting Qt < 5.6 code towards Qt 5.15 / Qt 6). Also, moving away from libdouble-conversion and towards standardized solutions (std::to_chars / std::from_chars) will also change output back to IEEE754's.

        No reviews matched the request. Check your Options in the drop-down menu of this sections header.

            cnn Qt Core & Network
            peppe Giuseppe D'Angelo
            Vladimir Minenko Vladimir Minenko
            Alex Blasche Alex Blasche
            Votes:
            0 Vote for this issue
            Watchers:
            6 Start watching this issue

              Created:
              Updated:

                There are no open Gerrit changes