How to make numbers not be shown in scientific form?

后端 未结 2 1106
礼貌的吻别
礼貌的吻别 2021-01-27 10:33

I want to write an array of floating point numbers into files



        
相关标签:
2条回答
  • 2021-01-27 11:23

    You should note that there is no such thing as "original form", as the float literal is already a different thing than the internal representation. Floats are by nature imprecise in the context of programming, and a lot of float numbers don't have a specific form that can be represented in decimal. This is why the best you can do is to set some kind of precision on them, like shown in the other answer.

    That is not related to PHP but to programming in general.

    If you have the same things stored as strings and not as floats, say:

    $x     = ['0.000455', '0.000123', '0.00005690330203'];
    $fname = 'test.txt';
    $str   = '';
    
    foreach($x as $elem) {
      $str .= "$elem\n";
    }
    
    file_put_contents($fname, $str);
    

    then you should have no issues in printing or writing them to a file.

    0 讨论(0)
  • 2021-01-27 11:26

    You can use the number_format function to set a precision:

    Example:

    $mynum = 24.2837162893;
    $mynum = number_format($mynum, 2);
    echo($mynum);
    
    // Outputs 24.28
    

    So if you decide you want all your numbers to have 10 decimal places, you would just use $mynum = number_format($mynum, 10);.

    Also, see the sprintf() function for other formatting options.

    [EDIT]

    In your particular example, here is where you would use this function:

    <?php
       $x=[0.000455,0.000123,0.00005690330203];
       $fname='test.txt';
       $str='';
       foreach($x as $elem){
          $str .= number_format($elem, 5) . "\n";
       }
       file_put_contents($fname,$str);
    ?>
    

    As described in the other answer, float values are inherently imprecise. You have to decide what precision is important to you in your use case.

    Ref: http://php.net/manual/en/function.number-format.php

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