This function is converting an array which may contain strings to numbers which may or may not have a decimal.
function toNumberArray(array $stringArray) {
print_r ($stringArray);
echo "<hr>";
$n = [];
for ($i = 0; $i < count($stringArray); $i++) {
$n[] = settype ( $stringArray[$i],"float");
$x = (float) $stringArray[$i];
echo $x;
echo "<br>";
}
return $n;
}
print_r (toNumberArray(["1.123456789012345","2.2000000000000002","3.2999999999999998"]));
Results:
Array ( [0] => 1.123456789012345 [1] => 2.2000000000000002 [2] => 3.2999999999999998 )
1.1234567890123
2.2
3.3
Array ( [0] => 1 [1] => 1 [2] => 1 )
Question:
Why is settype not converting the string to a float?
How to convert if there are 14 or more places after the decimal?
It is converting to a PHP float which is a 64-bit IEEE floating point number. You are probably expecting that PHP uses a 32-bit IEEE floating point number for float
and a 64-bit IEEE floating point number for a double'. But, in PHP
floatand
double` are synonyms. (see the link in jorgonor's comment).
You could use PHP's round
function to convert the 64-bit number to 6 or 7 decimal points to simulate the effect you are probably looking for. See http://php.net/manual/en/function.round.php