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 ?
source to share
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.
source to share
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
source to share