How to convert a string with either, or . as decimal/thousand separators into a float in PHP

1 Answer

0 votes
function toFloat(string $input): float {
    $commaCount = substr_count($input, ',');
    $dotCount = substr_count($input, '.');

    $lastComma = strrpos($input, ',');
    $lastDot   = strrpos($input, '.');

    $str = $input;

    if ($commaCount > 0 && $dotCount > 0) {
        if ($lastComma > $lastDot) {
            $str = str_replace('.', '', $str); // Remove thousand separators
            $str = str_replace(',', '.', $str); // Convert decimal
        } else {
            $str = str_replace(',', '', $str);
        }
    } elseif ($commaCount > 0) {
        $str = str_replace('.', '', $str);
        $str = str_replace(',', '.', $str);
    } else {
        $str = str_replace(',', '', $str);
    }

    return floatval($str);
}

echo number_format(toFloat("1,224,533.533"), 3) . PHP_EOL;
echo number_format(toFloat("1.224.533,533"), 3) . PHP_EOL;
echo number_format(toFloat("2.354,67"), 2) . PHP_EOL;
echo number_format(toFloat("2,354.67"), 2) . PHP_EOL;



/*
run:

1,224,533.533
1,224,533.533
2,354.67
2,354.67

*/

 



answered Jun 27, 2025 by avibootz
...