This will handle a string where it is unknown if comma or period are used as thousand or decimal separator. Only exception where this leads to a conflict is when there is only a single comma or period and 3 possible decimals (123.456 or 123,456). An optional parameter is passed to handle this case (assume thousands, assume decimal, decimal when period, decimal when comma). It assumes an input string in any of the formats listed below.
function 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>";
}