Reputation: 351
I am passing some variables to a function to round and add a dollars sign but when the values get into the function they have lost their values.
formatDollars($cost, $taxedCost, $shipping, $total)
function formatDollars($cost, $taxedCost, $shipping, $total) {
$taxedCost = '$'.round($taxedCost, 2);
$shipping = '$'.round($shipping, 2);
$total = '$'.round($total, 2);
$cost = '$'.round($cost, 2);
return array($cost, $taxedCost, $shipping, $total);
}
list($cost, $taxedCost, $shipping, $total) = formatDollars();
When I output I get the dollar signs but all my numbers have become zero.
Upvotes: 0
Views: 633
Reputation: 351
I ended up finding the answer to my own quesion
In the line that I send variables to the function it did not like not having a variable to equal to, so when I ended up saying my variables equalled sending to the function.
function formatDollars($numberFormatted)
{
$numberFormat = '$'.round($numberFormatted, 2);
return $numberFormat;
}
$cost = formatDollars($cost);
$taxedCost = formatDollars($taxedCost);
$shipping = formatDollars($shipping);
$total = formatDollars($total);
Upvotes: 0
Reputation: 21
When followed by $ sign it may considered as variable... You may follow below code
formatDollars($cost, $taxedCost, $shipping, $total)
function formatDollars($cost, $taxedCost, $shipping, $total) {
setlocale(LC_MONETARY, 'en_US');
$taxedCost = round($taxedCost, 2);
$taxedCost =money_format('%i', $taxedCost)
return array( $taxedCost);
}
Upvotes: 1
Reputation: 4334
What you are doing is a very round-about way of handling this. You want to change the values of the parameters, so make them pass-by-reference.
formatDollars($cost, $taxedCost, $shipping, $total);
function formatDollars(&$cost, &$taxedCost, &$shipping, &$total)
{
$taxedCost = '$'.round($taxedCost, 2);
$shipping = '$'.round($shipping, 2);
$total = '$'.round($total, 2);
$cost = '$'.round($cost, 2);
}
Now, the variables are passed in and any changes made to them inside the function actually change them. You don't need to return anything.
By the way - your function failed because the second call (with the list command) did not pass any parameters into the function.
Also - I would read up on number_format. If you round(3,2), you get 3, not 3.00.
Upvotes: 1