Efficient way to transform float to string

Ken Lerman lerman at stpstn.UUCP
Sun Dec 9 03:08:25 AEST 1990


In article <QbLnB1u00WBMM53Wpp at andrew.cmu.edu> rg2c+ at andrew.cmu.edu (Robert Nelson Gasch) writes:
->Hi,
->I'm looking for an *efficient* algorithm to transform a float (10< f < 0)
->into a string. What I am doing right no is this:
->
->I get the first digit and put the appropriate number in array[0]. 
->Array[1] gets the decimal point. I then make f < 1 and multiply it
->times 10, and get the aproriate character for the first digit and 
->repeat this procedure until the number equals 0. Sounds OK, but when
->you do this alot, it's pretty damn slow.
->
->If anybody has any suggestions on how to do this faster, please let me
->know. Both actual code or algorithm descriptions are welcome.
->
->Thanx alot --> Rob



You've got the right idea, but:

1 -- You should first convert the number from float to scaled integer.

2 -- Rather than multiplying by 10, shift left two, add the original
     and shift left again.  (A smart compiler might do this for you.)
     [Some might say that a reasonable compiler should do this for you.]

3 -- You didn't say how may digits of precision you want.  The
     multiple-precision scaled integer multiplication can be a pain if
     you want high precision.

Ken



More information about the Comp.lang.c mailing list