0

I need convert a currency string to decimal for storage it in a database of type "decimal (9,2)". Example:

0               =>  0.00
1               =>  1.00
1500            =>  1500.00
1500,50         =>  1500.00
1500.50         =>  1500.00
1.500           =>  1500.00
1.500,50        =>  1500.50
10.550.670,67   =>  10550670.00
1.506,0         =>  1506.00

I tried with preg_replace but I could not.

How can i solve this problem?

Edit #1: This is my function, the first preg_match work fine, now, i need convert the $number to format "xxxx.xx"

function formatNumber($number) {
    $isValid = preg_match("/^[0-9]{1,3}(?:[0-9]*(?:[.,][0-9]{2})?|(?:,[0-9]{3})*(?:\.[0-9]{2})?|(?:\.[0-9]{3})*(?:,[0-9]{1,2})?)$/", $number);
    if ($isValid) {
        return preg_replace("/^ THIS FAIL $/", "", $number);
    }
    return 0;
}

The number only have two digits, i can search for (,|.)[0-9]{2} and replace it with .[0-9]{2}. (sorry but i'm bad with regex).

Edit #2:

On my web, users can set a price, if the user is from US, he will use 1,222.33 or 1222.33, if the user is from Argentina, he will use 1.222,33 or 1222,33, now, i need convert the number to the format 1222.33 for storage it in a database with decimal type.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Manux22
  • 323
  • 1
  • 5
  • 16
  • [`floatval()`](http://php.net/manual/en/function.floatval.php) – Jan Apr 20 '16 at 16:13
  • what have done till now share code? – Santosh Ram Kunjir Apr 20 '16 at 16:14
  • 1
    you'll have to manually mangle the input numbers, since they're NOT valid php numbers. any auto-conversion (e.g. via typecasting) is going to outright fail on things like `1.500,50`, since `,` is not a valid numeric separator e.g. `str_replace(',', '.', str_replace('.', '', $num))` for SOME of those numbers. there's no one rule you can use for this, since your inputs are essentially random. `1500,50` v.s. `1500.50`. – Marc B Apr 20 '16 at 16:16
  • 2
    You need to start by coming up with a clear set of rules for the conversion. As it stands now, I can't see a clear pattern. – Patrick Q Apr 20 '16 at 16:17

2 Answers2

0

Because of the variance in your structures there isn't a one size fits all solution.

If EVERY possibility was using the comma as a decimal separator this would be trivial (via the code snipped that Marc B supplied) but your 4th item breaks that rule.

Nullsig
  • 38
  • 4
-3

Try this $variable= number_format((float)$variable, 0, '.00', '');

JonnyUK
  • 63
  • 1
  • 8