正在分析具有字符串流精度的浮点值

Parsing float with stringstream - precision?

本文关键字:精度 字符串      更新时间:2023-10-16

我使用字符串流来解析字符串中的浮点值。

std::stringstream strs(cp.val);
strs.precision(5);
strs<<std::setprecision(5);
float x; strs>>x;

然而,设置的精度函数似乎不起作用。。有什么方法可以强制解析而不是打印的精度吗?

precision(以及fixedscientific)只影响输出;输入将解析任何看起来像数值的内容,提取可能是任何数值一部分的所有字符。(这包括十六进制字符,以及整数输入时可能出现的"X"。)如果您想以任何方式限制格式,您必须将其作为字符串读取,验证格式,然后使用std::istringstream进行转换。

字符串语法不允许解析时的精度,但您可以在解析后设置双倍精度。

例如

#include <iostream>
#include <sstream>
#include <iomanip>
#include <cmath>
using namespace std; //do not use that in real project.
int main()
{
    // Initial declarations
    stringstream ss("13.321646");
    double x = 0.0;
    // Parse the double
    ss >> x;
    // Set the double precision to 2decimals
    double roundedX = round(x*100)/100;
    // output solution
    cout << x << endl;
    cout << setprecision(5) << x << endl;
    cout << roundedX << endl;
    return 0;
}

明显的注意:这是为了降低精度,而不是提高精度。