Jump to content

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.

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.