9

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 ;)

5
  • why without regex? That limits you greatly...
    – Nick
    Feb 2, 2012 at 10:18
  • 1
    So the input is variable, even when dots and zeroes might mean thousands separator or decimal point.. and you think that there's a magic hammer for this, for all possible inputs you might receive from your users?
    – N.B.
    Feb 2, 2012 at 10:18
  • @Nick I said "prefer" because I think regexp are hard to read and difficult to maintain. But I would still use them if I need to. Feb 2, 2012 at 10:30
  • @N.B. That is the fact we are facing see here and here. And so I think others had faced this problem before. A magic hammer would be nice! Feb 2, 2012 at 10:36
  • I get the issue you're having, but the problem is that you don't have the input that's constant. Sometimes you have 1,000.00 which represents a thousand. You an also have 1000.00 which is again 1 thousand. You can also have 100,00 which is a hundred (in my country we don't use the dot for decimal separator). So the question is how to interpret prices you encounter, it can vary. You need to set some ground rules, such as what's decimal separator and what's thousands separator. After that it's trivial to determine the price - skip everything that's not . or , or numeric character.
    – N.B.
    Feb 2, 2012 at 12:43

6 Answers 6

19

Ok, I tried it myself. What do you think of this?

function priceToFloat($s){
    // is negative number
    $neg = strpos((string)$s, '-') !== false;
    
    // 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);

    // Set negative number
    if( $neg ) {
        $s = '-' . $s;
    }

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

5
  • Seems like it should do the trick. Just out of curiosity, the filter_var approach didn't work for you?
    – Oldskool
    Feb 2, 2012 at 11:28
  • @Oldskool the filter_var solutions is very nice! But it does not work for prices without cents. Feb 2, 2012 at 11:39
  • You need to add the flag filter_var($price, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION); Dec 22, 2014 at 5:37
  • @JacobThomason I run my tests with this function but it fails in many cases even with a simple "1,00": codepad.org/Uax6Hnar Dec 22, 2014 at 9:02
  • Don't forget about negative numbers.
    – moorscode
    Oct 30, 2015 at 9:54
3

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.

2

This function will fix your problem:

function priceToSQL($price)
{
    $price = preg_replace('/[^0-9\.,]*/i', '', $price);
    $price = str_replace(',', '.', $price);

    if(substr($price, -3, 1) == '.')
    {
        $price = explode('.', $price);
        $last = array_pop($price);
        $price = join($price, '').'.'.$last;
    }
    else
    {
        $price = str_replace('.', '', $price);
    }

    return $price;
}
3
  • Thank you! This works very nice for most cases. I still found some examples the function has problems with like "22 000,76" and "22.000". I tried to build my own version. Feb 2, 2012 at 11:44
  • I fixed it with the cases you provided and it work perfectly now.
    – user1988125
    Feb 2, 2012 at 17:53
  • 1
    +1 Works fine now. Well done! This night a good an idea, I can do the same now in three lines. Check it out. Feb 3, 2012 at 7:06
2

price to number number to price examples

<?php

    $number="1.050,50";

    $result=str_replace(',','.',str_replace('.','',$number));
    echo $result. "<br/>";
    // 1050.50

    setlocale(LC_MONETARY, 'tr_TR');
    echo money_format('%!.2n', $result) ;
    // 1.050,50

?>
1
  • I added .UTF-8 to LC_MONETARY and tried my test strings but that did not work very well: codepad.org/s00IFyR5 Anyway money_format is interessting! Oct 30, 2015 at 9:43
1

To remove all but numbers, commas and full stops:

<?php

$prices = array( "1,00 €",
 "€ 1.00",
 "1'000,00 EUR",
 "1 000.99$",
 "1,000.01$",
 "1.000,10 EURO");

$new_prices = array();
foreach ($prices as $price) {
    $new_prices[] = preg_replace("/[^0-9,\.]/", "", $price);
}

print_r($new_prices);

Output:

Array ( [0] => 1,00 [1] => 1.00 [2] => 1000,00 [3] => 1000.99 [4] => 1,000.01 [5] => 1.000,10 )

Now lets utilize the parseFloat function from Michiel - php.net (I won't paste it here since it's a pretty big function):

<?php

$prices = array( "1,00 €",
 "€ 1.00",
 "1'000,00 EUR",
 "1 000.99$",
 "1,000.01$",
 "1.000,10 EURO");

$new_prices = array();
foreach ($prices as $price) {
    $new_prices[] = parseFloat(preg_replace("/[^0-9,\.]/", "", $price));
}

print_r($new_prices);

Output will be:

Array ( [0] => 1 [1] => 1 [2] => 1000 [3] => 1000.99 [4] => 1000.01 [5] => 1000.1 )
3
  • Nice, thank you! I tried Michiel function too but did not get it to work well. You solution has problems with "22 000,76" and "22.000". So I tried to build my own version. Feb 2, 2012 at 11:43
  • The above shouldn't have any problems with "22 000,76" assuming that it means "22000.76" and not "2200076.00". However your 2nd example won't work because it's not a float. A simple check on the 3rd last character would fix that though.
    – Nick
    Feb 2, 2012 at 11:55
  • Maybe I did something wrong, but parseFloat_Nick() did return some odd "0" for me. Feb 2, 2012 at 12:44
1

not perfect, but it work

function priceToFloat($s){
    // clear witespaces
    $s = trim($s);
    $s = str_replace(' ', '', $s);

    // is it minus value
    $is_minus = false;
    if(strpos($s, '(') !== false)
        $is_minus = true;
    if(strpos($s, '-') !== false)
        $is_minus = true;

    // check case where string has "," and "."
    $dot = strpos($s, '.');
    $semi = strpos($s, ',');
    if($dot !== false && $semi !== false){
        // change fraction sign to #, we change it again later
        $s = str_replace('#', '', $s); 
        if($dot < $semi) $s = str_replace(',','#', $s);
        else $s = str_replace('.','#', $s);

        // remove another ",", "." and change "#" to "."
        $s = str_replace([',','.', '#'], ['','', '.'], $s);
    } 
    $s = str_replace(',', '.', $s); 
    // clear usless elements
    $s = preg_replace("/[^0-9\.]/", "", $s);

    // if it minus value put the "-" sign
    if($is_minus) $s = -$s;
    return (float) $s;
}

working cases

$prices = [
    '123.456,789',
    '123,456.789',
    '123 456,789',
    '123 456.789',
    '-123,456.789',
    '(123,456.789)',
];
foreach($prices as $price)
     echo priceToFloat($price).'<br />';

return

123456.789
123456.789
123456.789
123456.789
-123456.789
-123456.789

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.