Search code examples
c++formathexfmt

How to format double as hex?


How can one format double as hex?

double t = 1.123;
fmt::format("{:x}", t);

It throws exception "invalid type specifier".

I would like to get string 3ff1f7ced916872b


Solution

  • You can use std::bit_cast to cast double into an appropriately sized integer and format that in hexadecimal, e.g. assuming IEEE754 double:

      double t = 1.123;
      auto s = fmt::format("{:x}", std::bit_cast<uint64_t>(t));
      // s == "3ff1f7ced916872b"
    

    godbolt: https://godbolt.org/z/ehKTrMz7M