skip to Main Content

PHP code:

$val1 = 32;
$val2 = 0.00012207031255;
$res = $val1 - $val2;
echo "echo: ".$res."n";
echo "json: ".json_encode($res)."n";
echo "form: ".number_format($res, 14);

Output:

echo: 31.999877929687
json: 31.99987792968745
form: 31.99987792968745

How to display 14 decimal places in echo without number_format()

I tried setting precision=14 in php.ini but nothing changed

3

Answers


  1. If you want to add a Global solution for the whole project without changing each line of code you can set ini_set('precision', 14) in the bootstrap file or set the same value in php.ini.

    To format a single value you can use sprintf() function with 14 decimal characters format.

    Code :

    $val1 = 32;
    $val2 = 0.00012207031255;
    $res = $val1 - $val2;
    echo sprintf("echo: %.14fn", $res);
    echo "json: ".json_encode($res)."n";
    echo "form: ".number_format($res, 14);
    

    Result :

    echo: 31.99987792968745
    json: 31.99987792968745
    form: 31.99987792968745
    
    Login or Signup to reply.
  2. You can try to use mathematical php module functions:

    php > $a = 32;
    
    php > $b = 0.00012207031255;
    
    php > echo bcsub($a, $b, 14);
    31.99987792968745
    

    More detail is here

    Login or Signup to reply.
  3. You can use sprintf()

    $val1 = 32;
    $val2 = 0.00012207031255;
    $res = $val1 - $val2;
    echo "echo: ".rtrim(sprintf("%.14f", $res), "0")."n";
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search