问题
I want to write an array of floating point numbers into files
<?php
$x=[0.000455,0.000123,0.00005690330203];
$fname='test.txt';
$str='';
foreach($x as $elem){
$str .= "$elem\n";
}
file_put_contents($fname,$str);
?>
but in the test.txt, I see
0.000455
0.000123
5.690330203E-5
I don't want the float point number to be shown in scientific/exponential form, I hope they keep the original form, besides, there are also large integers like 12430120340 so if I use special format for floating point numbers, like 0.000123293304 then maybe it is not suitable for large integers, maybe convert them into strings could be a good idea? but how?
回答1:
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
回答2:
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.
来源:https://stackoverflow.com/questions/13252645/how-to-make-numbers-not-be-shown-in-scientific-form