最后一个 getFloat() 函数并不完全正确。
1.000.000 和 1,000,000 以及它们的负数变体无法正确解析。为了比较和清晰起见,我将新函数的名称改为 parseFloat 而不是 getFloat
<?php
function parseFloat($ptString) {
if (strlen($ptString) == 0) {
return false;
}
$pString = str_replace(" ", "", $ptString);
if (substr_count($pString, ",") > 1)
$pString = str_replace(",", "", $pString);
if (substr_count($pString, ".") > 1)
$pString = str_replace(".", "", $pString);
$pregResult = array();
$commaset = strpos($pString,',');
if ($commaset === false) {$commaset = -1;}
$pointset = strpos($pString,'.');
if ($pointset === false) {$pointset = -1;}
$pregResultA = array();
$pregResultB = array();
if ($pointset < $commaset) {
preg_match('#(([-]?[0-9]+(\.[0-9])?)+(,[0-9]+)?)#', $pString, $pregResultA);
}
preg_match('#(([-]?[0-9]+(,[0-9])?)+(\.[0-9]+)?)#', $pString, $pregResultB);
if ((isset($pregResultA[0]) && (!isset($pregResultB[0])
|| strstr($preResultA[0],$pregResultB[0]) == 0
|| !$pointset))) {
$numberString = $pregResultA[0];
$numberString = str_replace('.','',$numberString);
$numberString = str_replace(',','.',$numberString);
}
elseif (isset($pregResultB[0]) && (!isset($pregResultA[0])
|| strstr($pregResultB[0],$preResultA[0]) == 0
|| !$commaset)) {
$numberString = $pregResultB[0];
$numberString = str_replace(',','',$numberString);
}
else {
return false;
}
$result = (float)$numberString;
return $result;
}
?>
与以下函数比较浮点数解析函数
<?php
function testFloatParsing() {
$floatvals = array(
"22 000,76",
"22.000,76",
"22,000.76",
"22 000",
"22,000",
"22.000",
"22000.76",
"22000,76",
"1.022.000,76",
"1,022,000.76",
"1,000,000",
"1.000.000",
"1022000.76",
"1022000,76",
"1022000",
"0.76",
"0,76",
"0.00",
"0,00",
"1.00",
"1,00",
"-22 000,76",
"-22.000,76",
"-22,000.76",
"-22 000",
"-22,000",
"-22.000",
"-22000.76",
"-22000,76",
"-1.022.000,76",
"-1,022,000.76",
"-1,000,000",
"-1.000.000",
"-1022000.76",
"-1022000,76",
"-1022000",
"-0.76",
"-0,76",
"-0.00",
"-0,00",
"-1.00",
"-1,00"
);
echo "<table>
<tr>
<th>String</th>
<th>floatval()</th>
<th>getFloat()</th>
<th>parseFloat()</th>
</tr>";
foreach ($floatvals as $fval) {
echo "<tr>";
echo "<td>" . (string) $fval . "</td>";
echo "<td>" . (float) floatval($fval) . "</td>";
echo "<td>" . (float) getFloat($fval) . "</td>";
echo "<td>" . (float) parseFloat($fval) . "</td>";
echo "</tr>";
}
echo "</table>";
}
?>