Jump to content

array_sum and trailing zero's


coupe-r

Recommended Posts

Hello everything,

 

I have the following code:

 

while($row = mysql_fetch_array($result))
{
     $due[] = $row['amount'];
     $total[] = $row['amount'];
}

    $due = array_sum($due);
    $total = array_sum($total);

 

My current output is:

 

$due = 23

$total = 100

 

What I would like is to have .00 at the end of each of those.

 

If either of the variables above naturally have decimals, they appear fine, just when they are integers.

 

Any help is appreciated.

Link to comment
https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/
Share on other sites

Hello Coupe-r

 

This is something off the top of my head...

  function addDecimal($value) {
    // Get length of value
    $length = strlen($value);
    // Get decimal places if any
    $getDecimal = substr($value,$length-3,$length-1);
    // Do preg match to check for decimals
    if(preg_match("/^\d+\.?\d{0,2}$/",$getDecimal)) {
      $value = $value.'.00'; // If no decimals add ".00"
    }
    return $value;
  }

 

Just pass each value though the function and it should in threory add .00 if no decimals exist.

If decimals do exist it won't do anything to the value.

 

Regards, Paul.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.