这将处理一个字符串,其中不知道逗号或句点用作千位分隔符还是小数分隔符。只有当只有一个逗号或句点且有 3 个可能的小数位时(123.456 或 123,456)才会导致冲突。一个可选参数被传递来处理这种情况(假设千位分隔符,假设小数分隔符,句点作为小数分隔符,逗号作为小数分隔符)。它假设输入字符串采用以下列出的任何一种格式。
toFloat 函数($pString,$seperatorOnConflict="f")
{
$decSeperator=".";
$thSeperator="";
$pString=str_replace(" ", $thSeperator, $pString);
$firstPeriod=strpos($pString, ".");
$firstComma=strpos($pString, ",");
if($firstPeriod!==FALSE && $firstComma!==FALSE) {
if($firstPeriod<$firstComma) {
$pString=str_replace(".", $thSeperator, $pString);
$pString=str_replace(",", $decSeperator, $pString);
}
else {
$pString=str_replace(",", $thSeperator, $pString);
}
}
else if($firstPeriod!==FALSE || $firstComma!==FALSE) {
$seperator=$firstPeriod!==FALSE?".":",";
if(substr_count($pString, $seperator)==1) {
$lastPeriodOrComma=strpos($pString, $seperator);
if($lastPeriodOrComma==(strlen($pString)-4) && ($seperatorOnConflict!=$seperator && $seperatorOnConflict!="f")) {
$pString=str_replace($seperator, $thSeperator, $pString);
}
else {
$pString=str_replace($seperator, $decSeperator, $pString);
}
}
else {
$pString=str_replace($seperator, $thSeperator, $pString);
}
}
return(float)$pString;
}
function testFloatParsing() {
$floatvals = array(
"22 000",
"22,000",
"22.000",
"123 456",
"123,456",
"123.456",
"22 000,76",
"22.000,76",
"22,000.76",
"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>thousands</th>
<th>fraction</th>
<th>dec. if period</th>
<th>dec. if comma</th>
</tr>";
foreach ($floatvals as $fval) {
echo "<tr>";
echo "<td>" . (string) $fval . "</td>";
echo "<td>" . (float) toFloat($fval, "") . "</td>";
echo "<td>" . (float) toFloat($fval, "f") . "</td>";
echo "<td>" . (float) toFloat($fval, ".") . "</td>";
echo "<td>" . (float) toFloat($fval, ",") . "</td>";
echo "</tr>";
}
echo "</table>";
}