C++26 brings a series of improvements to
std::format
, continuing the work started in C++20 and refined in C++23. These changes improve formatting consistency, runtime safety, and user ergonomics. There are so many of these updates, that I decided to divide them into two articles.
C++26: std::format improvement (Part 1)
by Sandor Dargo
From the article:
Arithmetic overloads of
std::to_string
andstd::to_wstring
usestd::format
P2587R3 by Victor Zverovich proposes replacing
sprintf
withstd::format
in the arithmetic overloads ofstd::to_string
andstd::to_wstring
.The motivation?
std::to_string
has long been known to produce not-so-great and misleading results (differing fromiostreams
), especially with floating-point values.std::to_string
uses the global C locale. In practice, it’s unlocalized. Also, it often places the decimal points to suboptimal places:std::cout << std::to_string(-1e-7); // prints: -0.000000 std::cout << std::to_string(0.42); // prints: 0.420000
These outputs are imprecise and often unnecessary. By leveragingstd::format
(and ultimatelystd::to_chars
), we now get clearer, shorter representations. The representations of floating-point overloads become also unlocalized and use the shortest decimal representations.As a result, the above outputs would change as follow:
std::cout << std::to_string(-1e-7); // prints: -1e-7
std::cout << std::to_string(0.42); // prints: 0.42
Add a Comment
Comments are closed.