Converting floating-point to string (sprintf)

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
User avatar
Masterkiller
Member
Member
Posts: 153
Joined: Sat May 05, 2007 6:20 pm

Converting floating-point to string (sprintf)

Post by Masterkiller »

How to convert floating-point numbers to ASCII values for displaying as a %f in sprintf. The way I need to display it is:
IntegerPart.Fraction
For Example: 5.25; 3.3333333 and so on.
Any ideas how to do this convert???
And %e for exponential display as: 1.3e+30 for example...
ALCA OS: Project temporarity suspended!
Current state: real-mode kernel-FS reader...
thooot
Member
Member
Posts: 30
Joined: Sun Jun 01, 2008 11:20 am

Re: Converting floating-point to string (sprintf)

Post by thooot »

A quick google search reveals that this is a hard problem. Here's a research paper that looks into it: http://www.cs.indiana.edu/~burger/FP-Pr ... PLDI96.pdf

Here's an approach that might work although there will most likely be rounding issues (warning: I haven't tested or even compiled this).

Code: Select all

void printDouble(double d) {
	double di, df;
	double  numDigits;
	
	if (d < 0) {
		printChar('-');
		d = fabs(d);
	}
	
	// Break the double into fraction (df) and integer (di) parts
	df = modf(d, &di);
	numDigits = floor(log10(di));
	
	// Calculate the integer portion to print
	while (di > 0.01) {
		double cur;
		double divBy = 1.0;
		
		// Get the 9 most significant digits
		if (numDigits > 9.0) {
			divBy = pow(10.0, numDigits - 9.0);
			numDigits = numDigits - 9.0;
		}
		
		cur = floor(di / divBy);
		printInteger((int) cur);
		
		di = di - (cur * divBy);
	}
	
	if (df != 0) {
		printChar('.');
	}
	
	// Calculate the fractional portion to print
	// TODO: Limit the maximum number of digits printed
	while (df != 0) {
		df *= 10;
		df = modf(df, &di);
		
		printInteger((int) di);
	}
}
The idea is to print the integer portion of the floating point number using a regular integer printing routine. 9 digits are done at once as that is the most an integer can handle (if you are using 64-bit integers you can increase this). It would be good to do the fractional portion the same way (9 digits at a time) in order to reduce the number of multiplications which are likely to introduce rounding errors. But I'm not sure of a good way of finding how many fractional digits there are.
Post Reply