Search code examples
phpformatlocale

PHP string to locale float


I trying to parse "2,249.90000000" into a float with local decimals. I want it to 2249,90000000. (nl_NL, money/eur)

I have tried multiple solutions like floatval or (float). Because number_format wants a number and not a string.

I didn't find the right solution on SO so, I created a new question, but I'm aware that this question is asked once.


Solution

  • You can use this code, code from the first note of floatval manual.

    If you want in 2249,90000000 check this demo

    <?php
    var_dump(tofloat("2,249.90000000"));
    
    function tofloat($num) {
        $dotPos = strrpos($num, '.');
        $commaPos = strrpos($num, ',');
        $sep = (($dotPos > $commaPos) && $dotPos) ? $dotPos :
            ((($commaPos > $dotPos) && $commaPos) ? $commaPos : false);
    
        if (!$sep) {
            return floatval(preg_replace("/[^0-9]/", "", $num));
        }
    
        return floatval(
            preg_replace("/[^0-9]/", "", substr($num, 0, $sep)) . '.' .
            preg_replace("/[^0-9]/", "", substr($num, $sep+1, strlen($num)))
        );
    }