Custom printf - Floats

Programming, for all ages and all languages.
Post Reply
User avatar
mark3094
Member
Member
Posts: 164
Joined: Mon Feb 14, 2011 10:32 pm
Location: Australia
Contact:

Custom printf - Floats

Post 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.
User avatar
mark3094
Member
Member
Posts: 164
Joined: Mon Feb 14, 2011 10:32 pm
Location: Australia
Contact:

Re: Custom printf - Floats

Post 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?
User avatar
mark3094
Member
Member
Posts: 164
Joined: Mon Feb 14, 2011 10:32 pm
Location: Australia
Contact:

Re: Custom printf - Floats

Post by mark3094 »

Yes, I am aware of the standard...
User avatar
qw
Member
Member
Posts: 792
Joined: Mon Jan 26, 2009 2:48 am

Re: Custom printf - Floats

Post 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.
User avatar
b.zaar
Member
Member
Posts: 294
Joined: Wed May 21, 2008 4:33 am
Location: Mars MTC +6:00
Contact:

Re: Custom printf - Floats

Post 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.
"God! Not Unix" - Richard Stallman

Website: venom Dev
OS project: venom OS
Hexadecimal Editor: hexed
Post Reply