PHP processing user-friendly formatted prices to standard floats
I have a form in which users can enter prices for items. Ideally I want the user to be able to add prices in whatever method feels best to them and also for readability. I then need to convert this to a standard float so that my web service can calculate costs开发者_Go百科 etc.
The part I'm struggling with is how to take the initial sting/float/int of currency and convert it into a float.
For example:
UK: 1,234.00
FRA: 1 234,00
RANDOM: 1234
RANDOM2: 1234.00
All of those have slightly different formats.
Which I would want to store as:
1234.00
I will then store the result in MySQL database as a DECIMAL.
Any help would be great.
Assuming you're using MySQL, use the DECIMAL or NUMERIC type are the correct types used for storing currency.
Float's are susceptible to rounding errors and have a limited precision.
The formatting for display should be handled by PHP.
If storing in DB, you should of course store a currency code - which can be used when retrieving to tell PHP how to display it
Couldn't you use:
floatval($AnyVar)
In a case where you'd like to accept so many different formats it's a bit tricky to get it right.
Now we can just use a simple regex to get the decimal and full parts of the value:
/^([0-9,. ]+?)(?:[.,](\d{1,2})$|$)/
The regex will capture the full part of the number + a decimal part, separated with a , or a . and which has one or two numbers.
The capture group 1 will contain the full part, and group 2 the decimal part (if any).
To get your number, you just need to filter out all non-numeric characters from the full part, and join the filtered full and decimal parts together.
If you want to make it more foolproof, you probably should implement something on the client-side to guide the user to input the value in the correct format.
精彩评论