Search code examples
phptransformationexponential

PHP outputting numbers in exponential form


When i'm outputting some of my double variables they're being written in exponential form using fwrite. Can i set some defaults in PHP where whenever a variable is displayed (copied or stored) it always happens in decimal format?

To be precise the problem occurs when i use the json_decode method on a json string which contains a double value (which is not in exponential form). That double value after converting an an object becomes exponential.


Solution

  • Assuming the numbers are still floats when being written (as opposed to strings), this is one way of doing it:

    echo rtrim(sprintf("%0.15f", $x), "0.");
    

    I'm not sure if there's a cleaner way or not. But basically this uses sprintf to print a maximum of 15 decimal places, and then trims off any trailing 0 or . chars. (Of course, there's no guarantee that everything will be rounded nicely with trailing zeros as you might expect.)

    If you just want a fixed size, then you can adjust the 15 and remove the rtrim.