Efficient way to transform float to string

Paul N. Hilfinger hilfingr at rama.cs.cornell.edu
Mon Dec 10 07:33:42 AEST 1990


In article <QbLnB1u00WBMM53Wpp at andrew.cmu.edu> rg2c+ at andrew.cmu.edu (Robert Nelson Gasch) writes:
>I'm looking for an *efficient* algorithm to transform a float (10< f < 0)
>into a string. What I am doing right [now] is ... [repeatedly peeling off the 
>most significant digit by truncation and subtraction, followed by 
>by 10.0, all in floating-point arithmetic.]
>If anybody has any suggestions on how to do this faster, please let me
>know. Both actual code or algorithm descriptions are welcome.

There have been a couple of responses to this posting suggesting the
use of gcvt or of scaling, conversion to integer, followed by
conversion to ASCII.  I was a little curious about these suggestions.
Some experimentation showed that on a DECstation 3100, using cc, Mr.
Gasch's original program is faster than either of the suggestions for
6 digits of result (at least for my C versions of his algorithm and
the alternatives).  I only find this interesting because it reminded
me (still one more time) that my intuitions about double-precision
floating-point performance---formed 20 years ago---need constant
re-examination.  (Needless to say, however, it would be unwise to
generalize my findings to other processors just now.)

Paul Hilfinger



More information about the Comp.lang.c mailing list