xiao Posted April 4, 2008 Share Posted April 4, 2008 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 https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/ Share on other sites More sharing options...
conker87 Posted April 4, 2008 Share Posted April 4, 2008 Why are you using commas in the first place? Use the dot, that's why it's called a decimal point. Link to comment https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/#findComment-509339 Share on other sites More sharing options...
xiao Posted April 4, 2008 Author Share Posted April 4, 2008 Because we use a comma in this country. Link to comment https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/#findComment-509380 Share on other sites More sharing options...
conker87 Posted April 4, 2008 Share Posted April 4, 2008 /slapsself Gah, apologies, totally forgot about the math punctuation deferences. Yes you'll probably have to change it to a period. Link to comment https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/#findComment-509385 Share on other sites More sharing options...
craygo Posted April 4, 2008 Share Posted April 4, 2008 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 https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/#findComment-509408 Share on other sites More sharing options...
kenrbnsn Posted April 4, 2008 Share Posted April 4, 2008 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 https://forums.phpfreaks.com/topic/99565-solved-array_sum-ignores-commas/#findComment-509421 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.