Page 1 of 1

Simple Question...

Posted: Fri Sep 03, 2004 6:45 pm
by Joe
How could I extract the the penny part of a price. For example if I had:

£51.32

How could I achieve the 32?. I thought regular expressions but not too sure.

Thanks


Joe 8)

Posted: Fri Sep 03, 2004 6:52 pm
by feyd
preg, something like:

Code: Select all

#£(\d*)(\.(\d*))?[^.\d]#

Posted: Fri Sep 03, 2004 6:56 pm
by Joe
Hmm would that be like:

Code: Select all

$alter = preg_match("#£(\d*)(\.(\d*))?[^.\d]#", $order->info['total']);
It does not seem to work, All I get is 0...

Posted: Fri Sep 03, 2004 7:23 pm
by Joe
Oh and sorry I forgot to mention, the price actually shows like:

51.32

So would your (feyd's) expression turn out like:

Code: Select all

$alter = preg_match("#(\d*)(\.(\d*))?[^.\d]#", $order->info['total']);

Posted: Fri Sep 03, 2004 7:26 pm
by feyd

Code: Select all

£(\d*)(\.(\d*))?[^.\d]?
seems to work..

Posted: Fri Sep 03, 2004 7:36 pm
by Joe
Does that work without the £ symbol.

Code: Select all

$alter = preg_match("#£(\d*)(\.(\d*))?[^.\d]?#", $order->info['total']);
The original price is 25.50 and with the new expression it shows 1. Perhaps there is a different technique?.

Posted: Fri Sep 03, 2004 8:12 pm
by feyd
uh... preg_match doesn't return the matches like that.. it returns if it found the pattern or not. Use the third argument to get the matches..

Posted: Fri Sep 03, 2004 8:32 pm
by Joe
Yeah its ok I got it, thanks. I was wondering though, when you said use the third argument to get the matches do you mean like:

Code: Select all

$alter = preg_match("#£(\d*)(\.(\d*))?[^.\d]?#", $order->info['total'], matches[0]);
Regular expressions is something I STILL need to catch up on, heh.

Posted: Fri Sep 03, 2004 8:44 pm
by feyd
read the doc page: [php_man]preg_match[/php_man]

Posted: Fri Sep 03, 2004 9:33 pm
by m3mn0n
And the non-regex way

Code: Select all

$price = 19.99;
$parts = explode (".", $price);
$dollars = (int) $parts[0];
$cents = (int) $parts[1];
If the variable had $, or another symbol in it, a simple [php_man]str_replace[/php_man]() would solve that problem. :)

Posted: Fri Sep 03, 2004 9:53 pm
by timvw
Generally i don't like regular expressions because of their performance hit...
Well, after a thread on comp.lang.php http://groups.google.be/groups?hl=nl&lr ... 26rnum%3D6

i changed my mind ;)

Posted: Fri Sep 03, 2004 10:02 pm
by ongray
this will work too...
$price = 19.99;
$cent = substr($price, -2); // returns "99"