简体   繁体   中英

Parsing float with stringstream - precision?

I am using stringstream to parse float from string.

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

however the set precision functions do not seem to work.. is there any way to force precision in parsing not printing ?

The precision (along with things like fixed and scientific ) only affect output; input will parse anything that looks like a numeric value, extracting all of the characters which could possibly be part of any numeric value. (This includes hex characters, and the 'X' which might occur for integral input.) If you want to limit the format in any way, you'll have to read it as a string, validate the format, and then use std::istringstream to convert it.

stringstram does not allow precision on parsing, but you may set the double precision after parsing.

Eg

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

Obvious note: That allow to reduce precision, not to improve it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM