Convert float to plain string representation

后端 未结 4 1510
隐瞒了意图╮
隐瞒了意图╮ 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 07:34

    Because sprintf() with "%.f" has trouble with expressions such as "1e-8", some text processing may be required:

    function convertFloat($floatAsString)
    {
        $norm = strval(floatval($floatAsString));
    
        if (($e = strrchr($norm, 'E')) === false) {
            return $norm;
        }
    
        return number_format($norm, -intval(substr($e, 1)));
    }
    

    Tested with:

    3          3
    1.5        1.5
    -15.482e-2 -0.15482
    1e-8       0.00000001
    1e+3       1000
    -4.66E-2   -0.0466
    3e-3       0.003
    

提交回复
热议问题