PHP: round a number to 16 decimal digits

Hi I am trying to round a number to 16 decimal digits but it only displays and does not round to 14 decimal digits.

Here's my attempt:

<?php

$num= 0.16346153846153846;

$round = number_format((float)$num, 17, '.', '');

echo $round * -1;
?>

      

OUTPUT:

-0.16346153846154

EXPECTED OUTPUT:

+0.1634615384615385

I know float is only 14 decimal digits. Is there any other way for 16 decimal digits ?

+3


source to share


4 answers


You can set these parameters at runtime. 16 digits are usually the maximum value on most platforms, high values ​​giving only meaningless or "fictional" digits:

ini_set("precision", "16");

      



See Changing precision level floating point variables

+3


source


Can you try this and see what happens? (Maybe not the best way to deal with floats and numbers)

$num = 0.16346153846153846;
$new_num = $num * -1;
echo number_format((float)$new_num, 17);

      



Multiply first, then try rounding the result.

0


source


number_format

and the INI parameter is precision

used float

, which can lead to unexpected behavior if you round to that many decimal digits.

Alternatively, you can use PHP decimal expansion with $decimal->toFixed(16)

or $decimal->round(16)

to achieve this with guaranteed precision regardless of your INI.

0


source


We recently had a problem reading a sum (decimal) from an Excel file that has a decimal number with more than 14 digits after the decimal number. The issue was addressed after using the extended algorithm option to convert decimal numbers. For this we need to install,

ini_set ("precision", -1);

Link: http://php.net/precision

0


source







All Articles