formatting currency for google merchant center - php

to use approved google merchant, I need to send them the price in this format:
2,00 EUR must been written as 2.00 ou 2.
100 000,00 EUR must be written 100000 or 100000.00, and not 100,000.00, 100,000 or +100,000.
Negatives values, like -20,14 EUR, must be written -20.14.
what I've got in my database actually is written like 100.000,00€
so to replace it, I've use:
$total_price = substr(str_replace(",", ".", str_replace(".", "", $order->info['total'])),0, -6);
Which is quite bad in my opinion. any thoughts on this?

You can use NumberFormatter::parseCurrency to parse a string into a double and a currency using the current formatter.

well regular expressions would help you keep things tidy, but you will still need to remove the dot you have lying around in there, and replacing the comma with a dot afterwards. once you have that, you can use
$str = preg_replace('/[^0-9.]+/', '', $str);
to eliminate any currency labeling you saved. Note to future you: when developing software for multi-currency transactions, you should separate values from currencies. this way you can keep a decimal value in the db and keep the type of currency in tnother and not bother with this all together.
have fun! let me know if you need anything else

Related

Comparing money amount in php

After having checked everywhere in vain I decided to post this problem here. I am Working on an online shop where the client needs to show automatically a "free shipping label" for all items that cost 100€ or more. I did make a function that worked with plain numbers (80€), but when the price is in this format (2.453,90€) it doesn´t.
I would really appreciate your help if you could shed some light on this issue. Thanks in advance
just remove dot and put dot instead of comma for php to recognize this as a number:
$plainNumber = floor(str_replace(",",".",str_replace(".","","2.453,90")));
if($plainNumber >= 100)
{
//do intended stuff
}
You could use regular expressions to transforms formatted numbers in raw numbers.
$number = preg_replace('/\./', '', $number);
$number = preg_replace('/,/', '.', $number);
You could also store raw numbers instead of formatted numbers.
Stringified data types are a not uncommon beginner error. You should always handle numbers as native numbers and only convert to string when printing them.
When you use numbers, good old comparison operators become useful.

Data validation on price PHP

I have the following problem. I need to validate and possibly extract currency from a value that I have received. The trouble starts with the fact that the value can be received in any encoding. Additionally to make things worse I can receive a lot of different values that should be considered correct. Let me give an example
$ 123,123,233.00
123,123.99
123.123.123,99
123.123.123 $
All of these are correct.
What I've tried is adding three arrays:
1. Chars (",","."," ")
2. Digits(0-9)
3. Currency Signs($,€...)
Trouble started when the data came in UTF-8 and I can no longer perform search digit by digit on the value I've received as in UTF-8 Currency signs are multibyte.
Question is what to do !?
I've tried the following thing.
Search for a currency sign. Then replace it with nothing. For some unknown reason PHP only replaces the second byte of the multibyte representation of the currency sign and there is a mysterious sign in the string that fails the whole check.
Any ideas are welcomed.
Datelligent idea may actually be a good simple solution: you could replace every non numerical character except the ones useful for puntuaction, with this regex \D*(?!\d{1,2}[\D$]):
$price=preg_replace('\D*(?!\d{1,2}[\D$])', '', $price);
It would transform 1233,234 234.23 into 1233234234.23.
Careful though, stuff like 123,2 34,234 would end up 123,2 34234. It does assume that punctuation followed by three or more digits isn't relevant, doesn't account for potential typos, will delete the currency symbol, etc... but it may be relevant to the scope of your issue.
Try this:
$price=$_POST['price'];
$price=preg_replace('/[^0-9]/', '', $price);
This way PHP will remove all characters and give you a string containing only numbers, which for handling prices is perfect.
If decimals are needed then modify the RegEx to get them:
$price=preg_replace('[0-9]+(\.[0-9][0-9]?)?', '', $price);

Number_format for arabic/persian numbers

I have a "price" field in a mysql database, which contains the price of a product in arabic or persian numbers.
Example of number: ۱۲۳۴۵۶۷۸۹۰ //1234567890
I cannot figure out how to format this so that it is formatted in a user-friendly way.
By that I mean, grouped by thousands or something similiar.
This would be ideal: ۱ ۲۳۴ ۵۶۷ ۸۹۰
number_format in php is what I would have used on latin numbers.
Is there any function which I don't know about, to make this possible?
If not, ideas of how to create one is appreciated.
Thanks
You could use a regex like this:
([۱۲۳۴۵۶۷۸۹۰])(?=(?:[۱۲۳۴۵۶۷۸۹۰]{3})+$)
Search and replace with \1, on the string ۱۲۳۴۵۶۷۸۹۰ would give you ۱,۲۳۴,۵۶۷,۸۹۰ (using , instead of space since SO trims them off. But using space in the replace instead will work just as well).
I would have to agree with the suggestion in the comments though, store the data using the numeric types available and convert them on input/output.
If you can store numbers in your database instead of strings (or convert to ascii numbers), then standard currency formatting with group-separators can be done with php5-intl functions. You just need ISO locale and currency codes:
$nf = new \NumberFormatter('fa_IR', \NumberFormatter::CURRENCY);
echo $nf->formatCurrency(1234.1234, 'IRR');
۱٬۲۳۴ ﷼
Otherwise, #rvalvik's answer is good.
See http://php.net/manual/en/class.numberformatter.php
More elegantly written than #rvalvik's regex pattern, you can add a comma after a character that is followed by 3, 6, 9, etc. characters.
Code: (Demo)
$str = '۱۲۳۴۵۶۷۸۹۰';
var_export(
preg_replace(
'~.\K(?=(?:.{3})+$)~u',
",",
$str
)
);
Output:
'۱,۲۳۴,۵۶۷,۸۹۰'
Here is similar answer to a related question.

Google finance API - trouble fetching currency rates

I'm using Google's currency API to fetch exchange rates and store them in my database, but I ran into some problems. Here's what I'm working with:
http://www.google.com/ig/calculator?hl=en&q=100USD=?GBP
I'm always passing 1USD as the first parameter and exchange that to all the currencies in my database, cast the result variable as a float and store it. Everything works fine until the result from the API is greater than 1000. For example:
http://www.google.com/ig/calculator?hl=en&q=100USD=?PYG
This returns "440 528.634" as the value, and the problem is in the space delimiter. When I cast that to a float it only stores "440". I tried running str_replace() on it before i cast it to a float, but for some reason that doesn't work - I'm guessing it's not a regular whitespace but a special character of some sort. I also tried exploding the variable by a space and returning the merged array fields, but no dice. I'm running out of ideas here so I really hope someone can help me on this :D
Its a non-breaking space character. You can replace it if you refer to it as \xA0:
$result = str_replace("\xA0", "", $result);
Note the double quotes. Use those instead of single quotes as it won't work correctly otherwise.
Its NO BREAK SPACE. You should refer to it as \xA0
$x = str_replace("\xA0", "", $x);
Should work.

Why is str_replace() only replacing one instance of a character in a string?

I have a large string variable that is assigned from a database column of type "Text" with Collation latin_swedish_ci.
Because it is in ASCII, I need to replace all non UTF-8 characters before I can put variable into my PDF generation script.
As we all know, the standards used by PDF are evil. If I use plain ASCII input it will go insane and cause a rip in space-time.
So in order to prevent anymore damage to our universe, I need help figuring out why this str_replace() function is only replacing one of a character type and ignoring any repeats of this character
Here is my code:
$tc = str_replace (array("\n", "£", "&"), array("<br/>", "£", "&"), $tc);
Input:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
Output:
Terms & Conditions: Mandatory charge of £10 for cancellations.
VAT E&EO
As you can see in the output on the second line the str_replace() does not change the ampersand character.
I wonder if this is because its over two lines or something like that.
So any idea how to get the function to work as I want it to, otherwise well your going to wake up with many Micro Blackholes vanishing your bowl of cereal tomorrow.
It looks like what you are trying to achieve could be done using these 2 functions:
nl2br(htmlentities($tc));
The benefit being that if your $tc variables gets any more HTML entities in the future, you won't have to fiddle with your str_replace().

Categories