Search code examples
phpnumbersscientific-notationnotation

How do I convert scientific notation string to float in PHP?


I have written a CSV importer and some of the values are very small, for example, in one of the CSVs I have 0.000024 which is being formatted as "2.40E-05" and when PHP puts that into the database it stores it as 2.4, I found an article that said if you add 1 to it, it changes to a float which is what I did and I got 1.000024, but if I then subtract 1, it goes back to being 2.4E-05, what is the best way in PHP to convert a scientific notation string to an actual float value? I would like to be able to store the value in my database as 0.000024.


Solution

  • You should convert to a string otherwise if you keep the float it will keep displaying with scientific notation

    $scientific = "1.828331E-9" ;
    $num=explode('-', $scientific);
    $precision=$num[1]+ strlen(filter_var($num[0], FILTER_SANITIZE_NUMBER_INT))-1;
    $float = number_format($scientific, $precision);
    echo "converted $float and back to original " . (float)$float;