Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am importing the csv file with ';' delimiter as a string and storing them in vector. But the data in my CSV have numbers with 15 or more decimal places which I need to preserve on conversion to double or long double.
Conversion from string to double in cpp(visual studio) rounds of to 4 decimal places. Is there a way I could parse the double values from csv directly as double or a round about to preserve my decimal places?

What I have tried:

I tried all possible conversion from string to double. (stold, stof, stod). Conversion from string to char*, char* to double. I read that its the compiler in visual studio that does this rounding off.
Posted
Updated 14-Dec-16 23:23pm

The C standard library functions atof and strtod are not rounding off any decimal places that can be hold by a double.

The rounding occurs probably when printing them out. To show all significant digits that can be hold by a double precision value use the [s]printf format "%.16G" (using the scientific format here to avoid leading / trailing zeroes for very small / large numbers).

A double precision value can hold 16 significant decimal digits (more precise: DBL_MANT_DIG * log10(2) = 15.95)

If the CSV has been created by printing double precision values, you should have no loss of precision besides those introduced by converting to string and back to floating point.

If the values in the file have more significant digits you must use a decimal number format. Note the term "significant" here. The CSV file may have been created by printing double precision values with more digits (e.g. using "%.18G") but the additional digits are not significant then (they are random).

Using long double is not an option with Visual C/C++ because it does not support operations with that type.

If you need a higher precision, use a C++ decimal type implementation like Chapter 1. Boost.Multiprecision - 1.62.0[^].
 
Share this answer
 
v2
Comments
CPallini 15-Dec-16 5:40am    
5.
Neither Visual Studio (which is an IDE) nor the compiler does any rounding.
Your code calls a library function to do the conversion and the library function would be responsible for any rounding.
It is most likely that you will end up calling, directly or indirectly, strtold or one of its cousins (depending on the character size). They DO NOT round to 4 decimal places.

If you read that the compiler does rounding then you should be looking elsewhere for your information.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900