首頁  >  文章  >  後端開發  >  如何以受控的精度和數字將浮點數精確轉換為字串?

如何以受控的精度和數字將浮點數精確轉換為字串?

Susan Sarandon
Susan Sarandon原創
2024-10-24 03:02:29860瀏覽

How to Precisely Convert a Float to a String with Controlled Precision and Digits?

具有精確度和數位控制的精確浮點到字串轉換

在C 中,將浮點轉換為字串涉及指定精度和數量十進制數字,確保準確的表示。

使用Stringstream:

常見的方法是使用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();

固定格式和Set precision:

  • fixed:確保浮點數值以特定小數位數顯示的定點表示法。
  • set precision:指定要顯示的小數位數

C 17 to_chars 系列:

對於技術轉換,C 17 引入了to_chars 系列:

<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>

有了這個方法,轉換返回具有指定精度和數字的字串,從而能夠準確表示一般和技術應用。

以上是如何以受控的精度和數字將浮點數精確轉換為字串?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn