Search code examples
phpmathfloating-pointscientific-notation

incorrect number from scientific notation in PHP


I'm reading data from spreadsheets that contain long numeric ID strings. I'm trying to make my system foolproof by making sure that the data reads correctly even if the column format is incorrectly set as a number.

So the spreadsheet contains the number 32486509223273700000 in scientific notation as 3.2486509223274E+19. Before i store it as a string i need to convert it to the original value. This is where the problems come in.

I can't make PHP convert the scientific notation back to the original number. Using various methods for converting the number back to original, it always seems to have different digits instead of trailing zeros.

$i = 3.2486509223274E+19;
echo $i; //32486509223274000384
echo number_format($i,0,'',''); //32486509223274000384
echo sprintf('%0.0f', $i); //32486509223274000384

Please note that I intend to store the end result as a string.


Solution

  • Note that the double floating point format has a precision of about 15.5 decimals. All other displayed decimals are extrapolated. And as always, extrapolation is a dangerous game.

    Or in other words, 3.2486509223274E+19 represents an interval, roughly from 3.24865092232739984E+19 to 3.24865092232740024E+19. Any integer in that interval has to count as "correct" extrapolation.