I like to convert string with a price to a float value. The price comes from different languages and countries and can look like this:
1,00 €
€ 1.00
1'000,00 EUR
1 000.00$
1,000.00$
1.000,00 EURO
or whatever you can think of...
Not sure I got the full range of possibilities with my examples. I am also not sure if it is possible to make in international convert blindly, maybe I have to use a language code? So for the start Euro and Dollar would be enough.
floatval()
is kind of stupid so I need something more here. I think I should first remove all chars beside numbers, ,
and .
. Then fix the ,
/ .
and use floatval finally.
Has someone done this before and can help me a little?
I would prefer a solution without regexp ;)
Ok, I tried it myself. What do you think of this?
function priceToFloat($s)
{
// convert "," to "."
$s = str_replace(',', '.', $s);
// remove everything except numbers and dot "."
$s = preg_replace("/[^0-9\.]/", "", $s);
// remove all seperators from first part and keep the end
$s = str_replace('.', '',substr($s, 0, -3)) . substr($s, -3);
// return float
return (float) $s;
}
Here some tests: http://codepad.org/YtiHqsgz
Sorry. I couldn't include the other functions because codepad did not like them. But I compared them and there was trouble with strings like "22 000,76" or "22.000"
Update: As Limitless isa pointed out you might have a look at the build in function money-format.
Removing all the non-numeric characters should give you the price in cents. You can then divide that by 100 to get the 'human readable' price. You could do this with something like the filter_var FILTER_SANITIZE_NUMBER_INT. For example:
$cents = filter_var($input, FILTER_SANITIZE_NUMBER_INT);
$price = floatval($cents / 100);
Above is untested, but something like that is probably what you're looking for.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With