They are using many special cases, and lots of awkward integer conversions and operations (to avoid any floating point operations, I'm sure). I made several versions (none longer that 50 lines); one with no floating point math, that used a table of integers to calculate the decimal value of the number, sort of like a fixed-point number, and some more integer math to convert the result to the right power of ten (the floating point exponent is in base-2) without losing accuracy. Another also used the table to get the decimal part, but used one floating point operation for the conversion stuff, and another one that used floating point math and a lookup function for integer base-10 exponentiations. The last one turned out to be the fastest (up to six times faster than printf, yay), and the most simple...Steel wrote:I cannot concieve of how, given an int to string function, it could take more than a hundred lines to make a float to string function.
I mean all you have to do is chop the float up into chunks, convert chunk to int and then to int to string.
eg pseudocode for a float thats f=123.456
int a=f;
String s1=intToString(a);
float b=f-a;
String s2=intToString(1000*b);
String result = s1+'.'+s2;
Return result;
All you have to do is to process the float into chunks and then cast those chunks to ints which cannot possibly take more than 100 lines.
It works like this:
1. Switch off the "sign bit" (but remember it when printing later)
2. Get the integer log10 of the floating point number
3. Use result to scale the number so it fits nicely in an int of appropriate size
4. Print integer, insert a dot where appropriate, or use scientific notation if it's way too large (use the log10 result for this)
5. Profit