Jump to content

[SOLVED] array_sum ignores commas


xiao

Recommended Posts

The array_sum function seems to ignore commas in numbers, so if I do for example:

1,5 + 2,9 + 3,7 it returns 6 instead of 8,1

Is there a way to fix this?

Or do I really have to replace all commas with dots, do array_sum and replace the dot with a comma again?  ???

Link to comment
Share on other sites

you can just make your own function. This one will add up the numbers for you, just put the number in an array.

 

<?php
function add_numbers($array){
  if(is_array($array)){
    foreach($array as $n){
    $numbers[] = str_replace(",", ".", $n);
    }
  $total = number_format(array_sum($numbers), 2, ',', ' ');
  } else {
  $total = "Numbers should be in an array";
  }
return $total;
}

$numbers = array("5,7", "5,9", "5,8");

echo add_numbers($numbers);
?>

 

Ray

 

Link to comment
Share on other sites

I know this is marked solved, but you can do the same thing using the array_map() function:

<?php
function comma_dot($str) {
return(str_replace(',','.',$str));
}

$numbers = array("5,7", "5,9", "5,8");
echo number_format(array_sum(array_map('comma_dot',$numbers)),2,',',' ');
?>

 

Ken

Link to comment
Share on other sites

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.