tags:

views:

156

answers:

4

It's a coding practice. I read these numbers as double from a file:
112233 445566
8717829120000 2.4
16000000 1307674.368
10000 2092278988.8
1234567 890123
After some computation, I should output some of them. I want to make them appear just the same as in the file, no filling zeros, no scientific notation, how could I achieve it? Do I have to read in as string then convert them?

Edit: Erm...Do you guys mean that there is actually no way for the program to know how the numbers look like originally?

+2  A: 

There's no built-in way to do this. Yes, you'll need to keep the original representation, and some link between that representation and the parsed number (a map<string, double> for example).

Dominic Rodger
+2  A: 

If you need to output the original numbers as they were, you might be better off storing the original strings somewhere. During the decimal -> binary -> decimal conversion, some precision may get lost, due to the precision limits of double. You may not end up printing the exact same decimal digits.

Ates Goral
+2  A: 

You read them as strings, record all the many finnicky aspects (do they have decimal parts, how long, any padding zeroes, etc, etc) and remember all those aspects for each field, convert them into numbers if you absolutely must, then use all the crazy little aspect you stored when formatting the numbers for output again. Crazy, but the only way to achieve literally what you're asking for.

Alex Martelli
+3  A: 

If you want the output to be identical to the input, then yes, you need to read them in as strings and store the strings to be output later.

Why? When dealing with floating point numbers, the computer can't represent most decimal fractional parts exactly in binary. So in a number like 2.4, the internal representation won't be exactly 2.4, it will be slightly different. Most of the time, the C/C++ I/O libraries will take such a binary number and print 2.4, but for some numbers, it might print something like 2.40000000001 or 2.399999999.

So, that's why you want to keep the original strings around.

Bob Murphy
I see. This is not so human...