问题描述
如何在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
:
A typical way would be to use 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
设置为固定
,浮点值使用定点表示法编写:该值的小数位数与 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.
和。
对于技术目的的转换,例如将数据存储在XML或JSON文件中,C ++ 17定义了函数家族。
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
}
这篇关于将浮点数转换为精度为&的字符串指定的小数位数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!