PHP - Serialize floating points

前端 未结 9 1479
自闭症患者
自闭症患者 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条回答
  •  萌比男神i
    2021-01-02 02:58

    Store them as integers (shift the first decimal place in front of the point by multiplying it by 10) and convert them back if you need it:

    function random_float($min,$max) {
        return ($min+lcg_value()*(abs($max-$min)));
    }
    
    $array = array();
    for ($i=0; $i<10; $i++) {
        $array[] = (int) round(random_float(6, 8) * 10);
    }
    $serialized = serialize($array);
    var_dump($serialize);
    
    $array = unserialize($serialized);
    foreach ($array as $key => $val) {
        $array[$key] = $val / 10;
    }
    var_dump($array);
    

提交回复
热议问题