Skip to content

Latest commit

 

History

History
39 lines (32 loc) · 1.12 KB

README.md

File metadata and controls

39 lines (32 loc) · 1.12 KB

Minimalistic C / D implementation of Fabian Loitsch's Grisu-algorithm [pdf]. Grisu converts floating point numbers to an optimal decimal string representation without loss of precision.

C Api

int fpconv_dtoa(double fp, char dest[24]);
  • Writes string representation of fp to dest and returns the number of written characters
  • The emitted string will never exceed 24 characters
  • Does not null terminate the string
  • Assumes fp is an IEEE 64-bit floating point number

Example usage

void print(double d)
{
    char buf[24 + 1]; /* reserve space for null terminator */
    int str_len = fpconv_dtoa(d, buf);

    buf[str_len] = '\0';
    printf("%s", buf);
}

Why not just use snprintf?

Convert doubles faster to shortest strings without precision loss.

Average processing time on a mix of "long" and "short" doubles in nanoseconds:

             short long
snprintf %g : 515  700
     %0.18g : 989  1171
         %f : 737  3047
fpconv_dtoa : 165  193

snprintf overhead : 71

Measured with gcc-4.8 -O3 and glibc 2.17.