gpt4 book ai didi

c++ - 将 float 转换为指定精度和小数位数的字符串?

转载 作者:IT老高 更新时间:2023-10-28 12:14:08 26 4
gpt4 key购买 nike

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

例如: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();

fixed

Use fixed floating-point notation

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

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函数族。

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

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

关于c++ - 将 float 转换为指定精度和小数位数的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200635/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com