PHP - Serialize floating points

前端 未结 9 1473
自闭症患者
自闭症患者 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: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);
    

提交回复
热议问题