Make calc element not rounding numbers

mkainz

Member
Hey! I've got a calc element with a code for sum repeating groups:

Here's my code:

$fields = array('generic_prices_77_repeat__price');
foreach ($fields as $field)
{
$value = JArrayHelper::getValue($data, $field . '_raw', array());
$thisSum = array_sum($value);
$total += $thisSum;
}
return (double)$total;

I've also tries with: return (float)$total; it is still rounding values....
 
Floating point numbers are not precise. You can eliminate the problem by removing the decimals (multiply by 100) and summing as integers. Then for your total, divide by 100 to add the decimals back again. Like this...
PHP:
$total = 0;
$fields = array('generic_prices_77_repeat__price');
foreach ($fields as $field)
{
   $thisSum = 0;
   $values = JArrayHelper::getValue($data, $field . '_raw', array());
   foreach($values as $value)
   {
       $thisSum += $value*100;
   }
   $total += $thisSum;
}
$total = $total/100;
/* or formatted as string (with comma for thousands seperator) */
// $total = number_format($total/100, 2, '.', ',');
return $total;
 
We are in need of some funding.
More details.

Thank you.

Members online

Back
Top