Reputation: 901
I have a text file which contains some values in each of the line like:
xxx.xxxxxx
I am reading each of the line and converting them to str using strod() and storing them in a temporary double variable.
when I print the value of that double variable, it outputs more digits than there should be after point.
The expected output should be:
xxx.xxxxxx
but I am getting
xxx.xxxxxxxxxxxxxxxx
using setprecision(20). Any idea why is this happening?. Also how can I read what's exactly in the file?
Upvotes: 0
Views: 185
Reputation: 154047
If you ask for 20 digits precision in output, you're going to get it. You seem to be surprised that you're getting something you explicitly requested. Anything other than 20 digits precision would surprise me.
As for what you read, typically, a number with 6 decimal places has no
exact representation in double; strtod()
will return the closest
approximation.
I would suggest not trying to use double
until you've read and
understood
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html.
double
is not a real number.
Upvotes: 4
Reputation: 258698
You are reading what's in that file, but you can't store the exact number. Not every number can be precisely represented as a double
(or anything else for that matter). Therefore, you'll get an approximation.
Upvotes: 2