php money to float

Reading time: less than 1 minute

php money to float

First Method:

$formatter = new NumberFormatter('pt_BR', NumberFormatter::CURRENCY);
var_dump($formatter->parseCurrency("R$ 75,25", $curr));
//return float(75.25)

Secound Method:

function getAmount($money)
{
    $cleanString = preg_replace('/([^0-9\.,])/i', '', $money);
    $onlyNumbersString = preg_replace('/([^0-9])/i', '', $money);

    $separatorsCountToBeErased = strlen($cleanString) - strlen($onlyNumbersString) - 1;

    $stringWithCommaOrDot = preg_replace('/([,\.])/', '', $cleanString, $separatorsCountToBeErased);
    $removedThousendSeparator = preg_replace('/(\.|,)(?=[0-9]{3,}$)/', '',  $stringWithCommaOrDot);

    return (float) str_replace(',', '.', $removedThousendSeparator);
}

var myFloat = getAmount('R$ 11,15');
var_dump(myFloat);
//return float(11.15)

This method is part of this library: https://github.com/mcuadros/currency-detector

If you use Laravel:

See this link: https://github.com/mcuadros/currency-detector