Page 1 of 1

Custom printf - Floats

Posted: Thu Apr 28, 2011 7:34 pm
by mark3094
Due to there being no standard C library, I have started to write the functions I need, such as printf (for x86).

Mostly, I can get this to work, but I am stuck trying to figure out how to handle the printing of floating point value (eg. printf("%f", floatnum);)

I have done this:

Code: Select all

fnum = va_arg(arglist, double);

printf("%d", (int)fnum);					/*  Print the integer part, truncate the fraction  */
putchar('.');								/*  Decimal point  */

if(fnum<0)									/*  If negative, remove the sign  */
	fnum = -fnum;
fnum = (fnum - (int)fnum) * 1000000;	/*  Get numbers after decimal point  */
printf("%d", (int)fnum);
However, this is not accurate enough. If I try to print 3.1415, it should print as 3.141500, instead it prints 3.141499. I would like this to be as accurate as the real printf.

I thought that I may be able to get the double and break it into it's compenents (sign, exponent and mantissa), but I don't think I can get the bits out of a double.

I don't want someone to do the work for me, but I do need a point in the right direction.
Thanks for your help.

Re: Custom printf - Floats

Posted: Thu Apr 28, 2011 9:34 pm
by mark3094
I have updated my method to the following:

Code: Select all

for(j=0; j<6; j++) {
	fnum -= (int)fnum;
	fnum *= 10.0;
	printf("%d", (int)fnum);
}
This will make it easier when I add precision to printf. However, the problem is that it is still changing the results (ie, 3.1415 becomes 3.141499).
Any thoughts as to why this is happening?

Re: Custom printf - Floats

Posted: Fri Apr 29, 2011 12:27 am
by mark3094
Yes, I am aware of the standard...

Re: Custom printf - Floats

Posted: Fri Apr 29, 2011 1:55 am
by qw
mark3094 wrote:Any thoughts as to why this is happening?
Perhaps 3.1415 or one of the intermediate results is not exactly representable in floating point format.

Re: Custom printf - Floats

Posted: Fri Apr 29, 2011 3:52 am
by b.zaar
Here's a printf I've been using http://home.comcast.net/~derelict/snippets.html It's designed for embedded systems, all you need to supply is a putchar function.