Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,086 questions

55,959 answers

573 users

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
...