skip to Main Content

I wrote a program that uses fmt library to convert floating point values in text. And recently I found that its output is distinct depending on operating system for exact integers. For example, using fmt package from Ubuntu 20 zero value is printed as 0.0 and using fmt package from Ubuntu 22, the same value is printed as 0.

As far as I see, the difference was introduced in between fmt v7.0.0 and v7.1.3.
This can be demonstrated using the simplified program as follows:

#include <iostream>
#include <fmt/format.h>

int main() {
    std::cout << fmt::format( "{}", 0.0 );
}

Online demo: https://godbolt.org/z/d8W3EbGhM

I would like to have exactly the same output of numbers produced by both fmt package from Ubuntu 20 and from Ubuntu 22 (it can be either 0.0 or 0, but the same on both). Is there a way to achieve this by some settings of fmt or by using some special format-string in place of {}, which does not limit the precision of output?

2

Answers


  1. They seemed to make a default format behavior for double type as it’s {:g}, that removes all trailing zeroes. Hence, use it

    #include <fmt/format.h>
    #include <iostream>
    
    int main() {
      std::cout << fmt::format("{:g}n", 0.0);  // outputs 0
    }
    
    Login or Signup to reply.
  2. You can use the # specifier to preserve the decimal point (and trailing zeros where appropriate). For example:

    std::cout << fmt::format("{:#}", 0.0);
    

    prints "0.0" on both versions (godbolt).

    Quoting the release notes:

    Changed the default floating point format to not include .0 for consistency with std::format and std::to_chars. It is possible to get the decimal point and trailing zero with the # specifier.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search