lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Hi all,

Am 2013-09-10 11:02, schrieb Tim Hill:
1. Serializing a float as a string is not, inherently, bad. Serializing it as a floating-point decimal literal string is, however, asking for trouble. There are plenty of string formats which provide perfect round-trip of IEEE-754 floats.

Just a small addition:
This (C++) code seems to do the job properly.
Certainly not perfect, but I've never found a problem in years of use.

Archives of the thread mentioned in the comment are at
http://www.velocityreviews.com/forums/t700600-float-to-string-to-float-with-first-float-second-float.html
https://groups.google.com/forum/#!topic/comp.lang.c++/hb4ff5tz3Ug
http://www.archivum.info/comp.lang.c++/2009-10/00935/float-to-string-to-float-with-first-float--second-float.html


/// This function serializes a given float f1 to a string s, such that:
///   - s is minimal (uses the least number of decimal digits required),
///   - unserializing s back to a float f2 yields f1==f2.
/// See my post "float to string to float, with first float == second float"
/// to comp.lang.c++ on 2009-10-06 for additional details.
static std::string serialize(float f1)
{
    // From MSDN documentation: "digits10 returns the number of decimal digits
    // that the type can represent without loss of precision."
    // For floats, that's usually 6, for doubles, that's usually 15. However,
    // we want to use the number of *significant* decimal digits here,
    // that is, max_digits10.
    // See http://www.open-std.org/JTC1/sc22/wg21/docs/papers/2006/n2005.pdf
    // for details.
    const unsigned int DIGITS10     = std::numeric_limits<float>::digits10;
    const unsigned int MAX_DIGITS10 = DIGITS10 + 3;

    std::string  s;
    unsigned int prec;

    for (prec = DIGITS10; prec <= MAX_DIGITS10; prec++)
    {
        std::stringstream ss;

        ss.precision(prec);
        ss << f1;

        s=ss.str();

        float f2;
        ss >> f2;

        if (f2 == f1) break;
    }

    wxASSERT(prec <= MAX_DIGITS10);
    return s;
}


Best regards,
Carsten


--
Dipl.-Inf. Carsten Fuchs

Carsten Fuchs Software
Industriegebiet 3, c/o Rofu, 55768 Hoppstädten-Weiersbach, Germany
Internet: http://www.cafu.de | E-Mail: info@cafu.de

Cafu - the open-source game and graphics engine for multiplayer 3D action