'Convert currency string to decimal PHP
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.
Solution 1:[1]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Nullsig |