Different decimal numbers in C?

Hello folks,

I'm sitting at my computer feeling a bit desperate right now.

The problem: I read a CSV file into C with floating point numbers of different sizes (in this case, that means that the numbers have different numbers of decimal places – e.g. 10.12 and 1.2356).

In the output, however, these numbers are always limited to six decimal places (I use the data type "double").

Is there a way to always output exactly the number that is stored in the CSV file?

So if 10.12 is in the CSV file, then 10.12 should be output. The same applies to 1.2356; here, 1.2356 should be output.

Thank you in advance for your feedback!

(2 votes)
Loading...

Similar Posts

Subscribe
Notify of
6 Answers
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
scatha
1 year ago

When converting into floating point type double, this information is lost, so it is not possible.

You know at “double”, definitely not whether there was 0.1700 or 0.17.

Thus, either the number of the specified decimal places should be additionally stored in an int value or the whole number should be stored as a string.

Do you read the CSV file with a library or “by hand”? Parsen is often a bigger task…

KarlRanseierIII
1 year ago
Reply to  scatha

Thus, either the number of the specified decimal places should be additionally stored in an int value or the whole number should be stored as a string.

Or just use a form of BCD, which, depending on further use, would be useful anyway – or alternatively something from the BEreich arbitrary precision, where this information is also used.

scatha
1 year ago

Yes, a data class that contains “everything necessary” and also the parsing and format functions would also be the most obvious approach, even for smaller projects. Probably there are such solutions already.
If it’s just about reading and spending, without further processing, you can also help yourself with simple strings.

When parsing CSV files that are output by a spreadsheet, you should also make sure that texts are in high-compile and can contain escape characters.

Therefore, a simple “split” function with separator “;” would be dangerous

This bike has also been built a hundred times

https://www.google.com/search?q=csv+parse+c%2B%2B

https://duckduckgo.com/?q=read+csv+file+in+c&t=h_&ia=web

J0T4T4
1 year ago
Reply to  scatha

The information is not really lost. Just don’t have to write out the trailing zeros.

scatha
1 year ago
Reply to  J0T4T4

Where is the information about the number of reported decimal places to be stored in a flow point value? Nowhere! 5,100 and 5,1 are the same value, but are expected to indicate different measuring accuracy.

guenterhalt
1 year ago

you mean something like printf(“%d”, variable);

then write printf(“%4d”, variable); // the number we then output 4 digits.