logoalt Hacker News

No portable way to detect string-to-float conversion errors in standard C

21 points • by signa11 • last Saturday at 3:39 PM • 14 comments • view on HN

Comments

Joker_vD • today at 6:00 AM

It's quite astonishing how the historical inability of commonly used programming languages (from FORTRAN all the way to, say, Java/C#) to ergonomically return two values from a function call has caused people to invent all kinds of insane APIs/contracts.

    [double x, errno_t errno] = strtod(s, nullptr);
    if (errno != 0) {
        // ...
    }

    [x, _] = strtod(s, nullptr);  // When you're certain the error is impossible or just don't care
Instead, we're stuck with "check if the return value is -1 and if it is, check the global variable errno" at best, and with "the function doesn't really reliably reports its errors so don't feed it malformed data, idc" at worst.
➕ show 1 reply
Panzerschrek • today at 5:36 AM

C number parsing functions are fundamentally broken, since they are locale-dependend. There are many bugs when one parses a number assuming it has decimal point, but later on systems with locale different from one used on developer's machine it may be suddenly comma instead of point. So, one should avoid using them almost always and use std::from_chars (available in new C++ versions) or some other thirdparty library.

➕ show 1 reply
chasil • today at 4:45 AM

IEEE-754 is a harsh mistress.

https://en.wikipedia.org/wiki/IEEE_754

➕ show 1 reply
anitil • today at 4:52 AM

Even putting aside the ugliness of errno, this is pretty bad. I'm at the point with libc where I try to use as little of it as I can, though I'm not writing a lot of C these days

➕ show 1 reply
j16sdiz • today at 4:23 AM

yes. that's why many number crunching app ships / vendors their own math library

TZubiri • today at 5:07 AM

" Dinesh: I said I would do DRM you would do error handling.

Gilfoyle: Anything to do with errors is more your vibe"

https://www.youtube.com/watch?v=oyVksFviJVE&t=49

Oh, this one is easy.

Just don't make the errors, then you don't have to detect them.

When your app stops issuing these errors, then you won't have to write blog posts complaining that someone elses code can't handle your errors.

Definitely you should never be converting strings to floats ever anyways, see how I'm going on a limb here without any knowledge of your application, but then you know that I'm right because there's no reason why you would ever do that?

CamperBob2 • today at 4:48 AM

     if (sscanf(string,"%lf",&foo) != 1) 
        { 
        bad_float(); 
        }
This has the benefit of handling scientific notation, too, which some of the other CRTL functions inexplicably do not.

For extra reassurance, initialize foo to NaN or DBL_MAX or something, and verify that it is no longer equal to that value.

➕ show 2 replies