Display float value w/o scientific notation

后端 未结 4 493
长发绾君心
长发绾君心 2020-11-27 20:00

When i make the following multiplication in PHP:

$ret = 1.0 * 0.000000001;

i get the result: 1.0E-9

I want to convert this result i

相关标签:
4条回答
  • 2020-11-27 20:39

    To align to your system's settings and limitations, you could use serialize_precision to get the most accurate result possible.

    echo rtrim(sprintf('%.'.ini_get('serialize_precision').'f', $ret));
    

    I do not recommend using the non-locale aware %F since your question only makes sense for display purposes. Respecting locale makes for a better UX.

    0 讨论(0)
  • 2020-11-27 20:52

    You need to add precision specifier (how many decimal digits should be displayed for floating-point numbers). Something like this:

    echo sprintf('%.10f',$ret);  // 0.0000000010
    

    If you have no idea what number you should specify, just give it a big number and combine it with rtrim().

    echo rtrim(sprintf('%.20f', $ret), '0');  // 0.000000001
    

    The code above will strip any 0's from the end of the string.

    0 讨论(0)
  • 2020-11-27 20:58

    I suggest the use BCMath for more accuracy when you are calculating with decimal numbers. That makes sure that you actually get the results you want.

    To print what you want, you should specify the precision and use %.9f, since it defaults to displaying 6 decimal numbers. That makes it something like this (just like bsdnoobz already said):

    sprintf('%.9f',$ret);
    
    0 讨论(0)
  • 2020-11-27 21:05

    sprintf('%f',$ret) doesn't work, it returns 0.000000. Overflow?

    sprintf works, however you miss some point here.

    0.000000 is not overflow. It's just that sprintf for the %f modifier uses 6 digits per default. Also please take care that %f is locale aware, %F is probably better suited.

    You might want to use more digits, e.g. let's say 4 000 000 (four million):

    $ php -r "printf('%.4000000F', 1*0.000000001);"
    
    Notice: printf(): Requested precision of 4000000 digits was truncated to PHP maximum of 53 digits in Command line code on line 1
    
    Call Stack:
        0.0001     319080   1. {main}() Command line code:0
        0.0001     319200   2. printf() Command line code:1
    
    0.00000000100000000000000006228159145777985641889706869
    

    As this example shows, there is not only a common value (6 digits) but also a maximum (probably depended on the computer system PHP executes on), here truncated to 53 digits in my case as the warning shows.

    Because of your question I'd say you want to display:

    0.000000001
    

    Which are nine digits, so you need to write it that way:

    sprintf('%.9F',$ret)
    

    However, you might want to do this:

    rtrim(sprintf('%.20F', $ret), '0');
    

    which will remove zeroes from the right afterwards:

    0.000000001
    

    Hope this is helpful.

    0 讨论(0)
提交回复
热议问题