PHP fputcsv showing scientific notation instead of long intergers

263 Views Asked by At

When creating file in csv using fputcsv then long integers show in scientific notation.

Example - 0133211000000140 is showing 1.33211E+14

    fputcsv($file, array('Id','DESTINATION_ACCOUNT','SOURCE_ACCOUNT'));
     if(!empty($data)){
        foreach($data as $key => $row){
            fputcsv($file,[$row['ID']
                               $row['DESTINATION_ACCOUNT'],  -- scientific notation instead of long integer
                               $row['SOURCE_ACCOUNT'] -- scientific notation instead of long integer
                        ]
                    );
        }
     }
1

There are 1 best solutions below

0
Pedro Amaral Couto On

That happens with floating points that have lots of digits:

https://www.php.net/manual/en/language.types.integer.php

If PHP encounters a number beyond the bounds of the int type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the int type will return a float instead. (...)

$large_number = 9223372036854775808;
var_dump($large_number);                     // float(9.2233720368548E+18)

echo gettype(1.33211E+14); outputs: double.

If you do printf('%d', '1.33211E+14');, or printf('%.0f', '1.33211E+14');, or echo (int)1.33211E+14;, you'll get a decimal representation. That representation might be wrong.

<?php
printf('%.0f', 66666666666666666);

outputted:

66666666666666664

If you're handling numbers larger than PHP_MAX_INT, it may be better to have them represented as strings and use GMP for the operations.