Home >Backend Development >C++ >How to Control Float-to-String Conversion Precision and Decimal Digits in C ?
When converting a float to a string in C , it is often necessary to control the precision and number of decimal digits displayed. Here's how this can be achieved:
A common approach is to use a stringstream:
<code class="cpp">#include <iomanip> #include <sstream> double pi = 3.14159265359; std::stringstream stream; stream << std::fixed << std::setprecision(2) << pi; std::string s = stream.str();
The fixed flag ensures that a fixed-point notation is used, while setprecision(2) specifies that only two decimal digits should be displayed.
For technical purposes, such as storing data in XML or JSON, C 17 introduces the to_chars family of functions:
<code class="cpp">#include <array> #include <charconv> double pi = 3.14159265359; std::array<char, 128> buffer; auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi, std::chars_format::fixed, 2); if (ec == std::errc{}) { std::string s(buffer.data(), ptr); // .... } else { // error handling }</code>
Here, std::chars_format::fixed ensures fixed-point notation, and 2 specifies the number of decimal digits.
The above is the detailed content of How to Control Float-to-String Conversion Precision and Decimal Digits in C ?. For more information, please follow other related articles on the PHP Chinese website!