I have just coded a basket/cart system for my websitye but I am sturggling on getting the total cost for items in the basket? I have the price for each item (i loop basket items in a loop) what the main question here is how can I add money strings together and get a valid money string total amount like below...
£4.56 + £2.35 + £3.00 = £9.91
£2.83 + £19.83 + £22 = £44.66 (I think)
you need to remove tha '£' from each item and then convert it to a integer then you create a variable named sum and in a loop you add each element to the sum , there you are the algorithm :
int sum = 0;
for_each (item i in basket)
{
string tmp = i.get_price() ; // get_price returns "£x" string
sum += to_integer(tmp.sub_str(1,tmp.length()-1));
/* copy from the pos 1 to the end ignoring the '£'*/
}
then the sum variable contains what you want :D
Use a number formatter:
$f = new NumberFormatter("en-GB",NumberFormatter::CURRENCY); //Make sure you use the correct locale
$total = 0;
foreach ($arrayOfCurrencies as $number) {
$c = $p = null;
$total += $f->parseCurrency($number, $c, $p);
}
return $f->formatCurrency($total,$c);
Don't use things like substring
for this when there's built-in ways to do it.