C++ 将浮点数转换为具有指定精度和十进制位数的字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29200635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 21:09:44  来源:igfitidea点击:

Convert float to string with precision & number of decimal digits specified?

c++stringfloating-point

提问by Shannon Matthews

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

在指定精度和十进制位数的同时,如何在 C++ 中将浮点数转换为字符串?

For example: 3.14159265359 -> "3.14"

例如: 3.14159265359 -> "3.14"

回答by AlexD

A typical way would be to use stringstream:

一种典型的方法是使用stringstream

#include <iomanip>
#include <sstream>

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

See fixed

固定

Use fixed floating-point notation

Sets the floatfieldformat flag for the strstream to fixed.

When floatfieldis 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.

使用固定浮点表示法

floatfieldstr流的格式标志设置为fixed.

floatfield被设定为fixed,浮点值使用定点表示法写成:该值与完全一样由指定的小数部分的数位表示的精度字段precision)中,用无指数部分。

and setprecision.

setprecision



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

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

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
}

回答by Mats Petersson

The customary method for doing this sort of thing is to "print to string". In C++ that means using std::stringstreamsomething like:

做这种事情的习惯方法是“打印到字符串”。在 C++ 中,这意味着使用std::stringstream类似的东西:

std::stringstream ss;
ss << std::fixed << std::setprecision(2) << number;
std::string mystring = ss.str();

回答by Columbo

Another option is snprintf:

另一种选择是snprintf

double pi = 3.1415926;

std::string s(16, '
#include <fmt/core.h>

int main()
  std::string s = fmt::format("{:.2f}", 3.14159265359); // s == "3.14"
}
'); auto written = std::snprintf(&s[0], s.size(), "%.2f", pi); s.resize(written);

Demo. Error handling should be added, i.e. checking for written < 0.

演示。应该添加错误处理,即检查written < 0.

回答by vitaut

You can use the fmt::formatfunction from the {fmt} library:

您可以使用该fmt::format功能从{} FMT库

    float number = 3.14159;
    std::string num_text = std::to_string(number);
    std::string rounded = num_text.substr(0, num_text.find(".")+3);

where 2is a precision.

2精度在哪里。

This formatting facility has been proposed for standardization in C++: P0645. Both P0645 and {fmt} use a Python-like format string syntax which is similar to printf's but uses {}as delimiters instead of %.

已建议将此格式化工具用于 C++ 中的标准化:P0645。P0645 和 {fmt} 都使用类似 Python 的格式字符串语法,它类似于printf's 但{}用作分隔符而不是%.

回答by Sebastian R.

Here a solution using only std. However, note that this only rounds down.

这是仅使用 std 的解决方案。但是,请注意,这只会向下取整。

3.14

For roundedit yields:

因为rounded它产生:

float num=99.463;
float tmp1=round(num*1000);
float tmp2=tmp1/1000;
cout << tmp1 << " " << tmp2 << " " << to_string(tmp2) << endl;

The code converts the whole float to string, but cuts all characters 2 chars after the "."

该代码将整个浮点数转换为字符串,但将“.”后的所有字符剪切为 2 个字符。

回答by Kemin Zhou

Here I am providing a negative example where your want to avoid when converting floating number to strings.

在这里,我提供了一个反面示例,您在将浮点数转换为字符串时希望避免这种情况。

99463 99.463 99.462997

You get

你得到

string ftos(float f, int nd) {
   ostringstream ostr;
   int tens = stoi("1" + string(nd, '0'));
   ostr << round(f*tens)/tens;
   return ostr.str();
}

Note: the num variable can be any value close to 99.463, you will get the same print out. The point is to avoid the convenient c++11 "to_string" function. It took me a while to get out this trap. The best way is the stringstream and sprintf methods (C language). C++11 or newer should provided a second parameter as the number of digits after the floating point to show. Right now the default is 6. I am positing this so that others won't wast time on this subject.

注意:num 变量可以是接近 99.463 的任何值,您将得到相同的打印输出。关键是要避免方便的c++11“to_string”函数。我花了一段时间才摆脱这个陷阱。最好的方法是stringstream 和sprintf 方法(C 语言)。C++11 或更新版本应该提供第二个参数作为要显示的浮点数后的位数。现在默认值是 6。我设置这个是为了让其他人不会在这个主题上浪费时间。

I wrote my first version, please let me know if you find any bug that needs to be fixed. You can control the exact behavior with the iomanipulator. My function is for showing the number of digits after the decimal point.

我写了我的第一个版本,如果您发现任何需要修复的错误,请告诉我。您可以使用 iomanipulator 控制确切的行为。我的功能是显示小数点后的位数。

##代码##