# Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End Adding currency values

• This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
• Author
Posts
• #160407
TWG
Participant

I’m storing values in an array like so.
\$holder = array(
“1” => “100.12”,
“2”=> “232.45”,
“3”=> “459.18”
);

I have multiple arrays like this that I need to add to a \$total variable. Can I add currency like this or do I need to do it differently.

#160417
__
Participant

I have multiple arrays like this that I need to add to a \$total variable.

Meaning, you want to total all values in all of your arrays? or you want to total each index in all of your arrays?

Can I add currency like this or do I need to do it differently.

Differently.

Your values are defined as strings, not as numbers.

They have decimal points in them, so when you start doing math on them, they’ll be converted to floatsâ€¦ which is the single worst data type to do decimal math (see the “floating-point precision” warning here).

Now, especially when dealing with money, there is an expectation that your arithmetic will be correct. They safest way to ensure this is to make sure you use integers: multiply all values by 100 and do your math on cents instead of dollars. If you’re doing multiplication or division (e.g., calculating percentages or averages) where you need greater precision, you might want to use a bigger factor.

#160421
Alen
Participant

To get you started:

\$data = [
"1" => 10012,
"2" => 23245,
"3" => 49518
];

function bling_bling(\$cents){
return \$cents / 100;
}

echo "\$ " . bling_bling(array_sum(\$data));

Just make sure array values are numeric like @traq said and use cents.

#160423
__
Participant

To explain my earlier question, take these arrays as an example:

\$a1 = [
1 => 100,
2 => 200,
3 => 300
];

\$a2 = [
1 => 101,
2 => 102,
3 => 103
];

Which is the result you are looking for?

\$r1 = [
1 => 201,
2 => 302,
3 => 403
];

\$r2 = [
1 => 500,
2 => 305
];

\$r3 = 805;

Viewing 4 posts - 1 through 4 (of 4 total)
• The forum ‘Back End’ is closed to new topics and replies.