Convert float to plain string representation

后端 未结 4 1527
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 07:24

SO,

The problem

My question is about trivial thing: how to convert numeric string to it\'s plain (\"native\") representation. That means: if

4条回答
  •  独厮守ぢ
    2020-12-31 08:00

    For those who just wants to convert float to string.

    function float_to_string($float)
    {
        $string = (string)$float;
    
        if (preg_match('~\.(\d+)E([+-])?(\d+)~', $string, $matches)) {
            $decimals = $matches[2] === '-' ? strlen($matches[1]) + $matches[3] : 0;
            $string = number_format($float, $decimals,'.','');
        }
    
        return $string;
    }
    
    $float = 0.00000000020001;
    
    echo $float; // 2.0001E-10
    echo PHP_EOL;
    echo float_to_string($float); // 0.00000000020001
    echo PHP_EOL;
    
    $float = 10000000000000000000000;
    
    echo $float; // 1.0E+22
    echo PHP_EOL;
    echo float_to_string($float); // 10000000000000000000000
    echo PHP_EOL;
    

提交回复
热议问题