strtold parsing lower number than given number

I’ll cut right to the chase: I am trying to parse a string with strtold to get a long double, but it is giving me the wrong value. Specifically, I am parsing the number 97777777777777777777777777777777777777.0, but strtold parses it as 97777777777777777779155292002375958528.000000. I check errno, HUGE_VALL, and end_ptr, but errno does not report an error, my number is no where near HUGE_VALL, and end_ptr is empty. I’ve been trying to debug this for a while, but I’m at my wits end. I don’t think this is a bug in strtold because the same problem happens if I take out some 7’s from the number. This code works for small numbers, like 97. I would greatly appreciate it if someone could help me here.

The code:

#include <stdio.h>          // printf
#include <stdlib.h>         // strtold
#include <errno.h>          // errno
#include <string.h>         // strerror
#include <math.h>           // HUGE_VALL

int main(int argc, char** argv)
    char* theNum = "97777777777777777777777777777777777777.0";
    printf("HUGE_VALL = %Lfn", HUGE_VALL);    // just to make sure I'm not insane
    char* endbuf;
    errno = 0;
    long double n = strtold(theNum, &endbuf);
    if (n == HUGE_VALL && errno != 0)
    { printf("strtold err: %sn", strerror(errno)); }
    { printf("strtold status: %sn", strerror(errno)); }
    printf("the number: %Lfn", n);
    printf("endbuf: %sn", endbuf);
    return 0;


strtold status: Success
the number: 9777777777777777777835998445568.000000

Some details:

64-bit Red Hat Linux: (uname -i says x86_64)

Running Red Hat Enterprise Linux Server release 7.1 (Maipo)

gcc (GCC) 4.8.3 20140911 (Red Hat 4.8.3-9)

I’m compiling using c99: c99 primefactors_test.c ../../src/primefactors.c -o primefactors_test -I../../include/ -O3 -lm

I also tried a simpler compile statement where I take out all of the unneeded dependencies: c99 primefactors_test.c -o primefactors_test -lm

Source: gcc

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.