coupe-r Posted September 12, 2010 Share Posted September 12, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/ Share on other sites More sharing options...
PaulRyan Posted September 12, 2010 Share Posted September 12, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/#findComment-1110246 Share on other sites More sharing options...
sasa Posted September 12, 2010 Share Posted September 12, 2010 look function number_format() Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/#findComment-1110247 Share on other sites More sharing options...
coupe-r Posted September 12, 2010 Author Share Posted September 12, 2010 Thank you for taking the time to do that. I also found this: number_format($total, 2, '.', '') Would that do the same? Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/#findComment-1110248 Share on other sites More sharing options...
coupe-r Posted September 12, 2010 Author Share Posted September 12, 2010 Looks like it will. Thank you. Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/#findComment-1110249 Share on other sites More sharing options...
Pikachu2000 Posted September 12, 2010 Share Posted September 12, 2010 money_format() may also be useful . . . Quote Link to comment https://forums.phpfreaks.com/topic/213217-array_sum-and-trailing-zeros/#findComment-1110250 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.