PHP - Serialize floating points

前端 未结 9 1416
自闭症患者
自闭症患者 2021-01-02 02:19

I am generating 10 random floats between 6 and 8 (all for good reason), and writing them to a mysql database in a serialized form. But one quirk seems to emerge at the stora

相关标签:
9条回答
  • 2021-01-02 03:17

    Setting your serialize_precision value in php.ini to -1 will solve the floating point issue, or you can set it to a value that you prefer, as per the specifications here: http://php.net/manual/en/ini.core.php#ini.serialize-precision

    PHP versions <= 5.3.5 shipped with the default value of "100", while the default now at version 7.0.33 is "17", although the package bundled with your distro might have shipped with a "-1"

    As pointed out in other responses, you can override this setting in the application itself or even a custom php.ini that your VirtualHost container or .htaccess specifies.

    I hope that helps :)

    0 讨论(0)
  • 2021-01-02 03:19

    PHP.INI file contains a serialize_precision directive, which allows you to control how many significant digits will be serialized for your float. In your case, storing just one decimal of numbers between 6 to 8 means two significant digits.

    You can set this setting in php.ini file or directly in your script:

    ini_set('serialize_precision', 2);
    

    If you do not care about the exact number of significant digits, but care about not having a spaghetti of digits resulting from the way float numbers are stored, you can also give a go to a value of -1, which invokes "special rounding algorithm", this is likely to do exactly what is required:

    ini_set('serialize_precision', -1);
    

    You can even reset it back to its original value after your serialization:

        $prec = ini_get('serialize_precision');
        ini_set('serialize_precision', -1);
    
        ... // your serialization here
    
        ini_set('serialize_precision', $prec);
    
    0 讨论(0)
  • 2021-01-02 03:24

    For me I found 3 ways:

    1. convert float to integer after float var is multiplied to a big number (for example 1,000,000); it's not a very convenient way as you should not forget to divide by the same 1,000,000 it when it's used
    2. to use preg_replace('/d:([0-9]+(\.[0-9]+)?([Ee][+-]?[0-9]+)?);/e', "'d:'.((float)$1).';'", $value); where $value is your float; found here
    3. also, to round the float by round() and store it in array as string.

    In any case I use variant #2

    0 讨论(0)
提交回复
热议问题