使用精度 & 将浮点数转换为字符串指定的小数位数?

2022-01-09 00:00:00 string floating-point c++

如何在 C++ 中将浮点数转换为字符串,同时指定精度 &小数位数?

How do you convert a float to a string in C++ while specifying the precision & number of decimal digits?

例如:3.14159265359 ->3.14"

推荐答案

典型的方法是使用 stringstream:

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

参见固定

使用固定浮点表示法

将 str 流的 floatfield 格式标志设置为 fixed.

Sets the floatfield format flag for the str stream to fixed.

floatfield 设置为 fixed 时,浮点值使用定点表示法写入:该值用与小数部分中的位数完全相同的数字表示由 precision 字段 (precision) 指定并且没有指数部分.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

和setprecision.

对于技术目的的转换,例如将数据存储在 XML 或 JSON 文件中,C++17 定义了 to_chars 系列函数.

For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

假设一个兼容的编译器(我们在撰写本文时缺乏),可以考虑这样的事情:

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

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

相关文章