简体   繁体   中英

C++ String to float with precision

I have a file with number readings (example 5.513208E-05 / 1.146383E-05) I read the file and store the entries in a temporary string. After that I convert the temporary string into float variable (which I store in an Multi Dimensional Array). I use the code below to convert.

getline(infile, temporary_string, ',');

Array[i][0] = ::atof(temporary_string.c_str());

getline(infile, temporary_string);

Array[i][1] = ::atof(temporary_string.c_str());

The problem is that when I print the floats to the screen

5.51321e-05 1.14638e-05 instead of 5.513208E-05 1.146383E-05

How can I get the precise numbers stored ???

You don't specify precision when you read or convert the string. Instead you set the precision when you output the value:

std::cout << std::setprecision(3) << 1.2345 << '\n';

The above will produce the following oputput:

1.23

See eg this reference .

Ensure you have double Array[][] , not float . A text presentation (base 10) is always approximated by the binary floating point number (base 2), but with luck approximated number of atof has the same presentation, when using the same format. In general one does not do much calculation, and on output uses a reduced precision with setprecision or formats.

Every floating-point representation of numbers has limited precision. In particular, float has 24 bits (1 fixed+23 variable) for its binary mantissa, thus implying a precision of roughly seven decimal digits.

If you need more precision for the stored number, you may wish to consider using double instead of float . On normal PCs, double has 53 bits (1+52) for the binary mantissa, thus allowing a 15-decimal digit precision.

But remember that there's also a problem when those numbers are output. I think the default precision for both printf () and std::ostream is only 6 digits, both for float and for double , unless you specify otherwise. There is no point, however, in demanding a higher precision during output than what the data type provides. So, even though you can say printf("%0.30g", some_float) , the extra 23 digits beyond the seven actually supported by the data type might not really produce useful information.

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