? write and read double as text reliably

Apperson H Johnson apperson at brahms.udel.edu
Fri Jan 18 08:17:04 AEST 1991


What is the best way to write double precision numbers if
1. they are to be read by people
2. they are to bre read by a C program, and MUST preserve their exact values.

I need a general format that will preserve all the significant bits of any 
double I write.

I have tried "%.30g" with the following results

2 of 4 systems tried do NOT preserve the values of the floats
across sprintf/sscanf (I tried Xenix 386, SCO Unix, AIX 3.1, Sun OS)

NOTE that NO TWO systems printed EXACTLY the SAME values !!! 

Is there a portable, general solution to this problem? 

It would be nice if system A could read what it wrote (exactly)
it would be REAL nice if for any two systems (A,B) A could read
what B wrote (exactly) - don't any standards cover this ? 

---------------------  tear on dotted line ------------------------------------
#include <stdio.h>

char *s1 = "0.12345678901234547890123456789012345678901234567890";
/* note that i dont REALLY expect all of these digits to affect the value,
   i just want to guarantee excess significant digits */


char s2[128];

main()
{
	double d1, d2, atof();
	
	d1 = atof(s1);
	sprintf(s2,"%.60g",d1);
	sscanf(s2,"%lf",&d2);
	
	printf("d1 and d2 are %sequal!\n", d1 == d2 ? "" : "NOT ");
	printf("s1 = %s\nd1 = %.60g\ns2 = %s\nd2 = %.60g\n",
	   s1,d1,s2,d2);
		
}

----------------------- cry on dotted line ------------------------------------

thanks for any help you can offer,
apperson at brahms.udel.edu



More information about the Comp.unix.aix mailing list