Calculate sum using sum api question
Calculate sum using sum api question
islamelshobokshy
Posts: 99Questions: 20Answers: 1
I'm trying to calculate the sum by following this code : https://phppot.com/jquery/calculate-sum-total-of-datatables-column-using-footer-callback/
But I've got a question. How to make it sum the numeric value inside data-order rather than the string in the td itself?
When it goes that, I'll have to remove all .reduce() from the code in the link above right ?
This discussion has been closed.
Replies
Hi @islamelshobokshy ,
That example looks similar to this one on the DataTables site. The conversions on there are worth a look. Or if it's a string, and you want to convert to an integer, use the JavaScript
parseInt()
function.Cheers,
Colin
Thank you @colin once again for your reply.
The link you gave me transforms my string into a number, but I'm using data-order, and inside of it is the number I want to use, how to write a sum using that data-order number and not the string itself?
Ah, I missed that. Look at this example here, live.datatables.net/roxoxiwi/1/edit, if you use
render('sort')
to get the "data-order" value.Cheers,
Colin
@colin do you have an idea how to calculate the average using the same idea? Replacing the strings and calculating the average rounded by 2 numbers after the decimal?
This plug-in will give you the average of the data in the result set.
Allan
@allan it doesn't take into consideration the unformatted field, so it doesn't work. I was thinking about summing everything (that I already did), and then divide that result on the number of rows to get the average. But I can't find a way to get the number of rows. This is what I want to do :
I have 'sum', but I need the number of rows. Any ideas?
You can get the total number of rows using the
count()
method - so,table.rows().count()
C
@colin thank you for your kind reply! I tried inside my footerCallback getting it this way, but the result is a 0, which isn't the count.
I used api.flatten().length as per the documentation it is the same thing as count().
No, it's not the same thing,
flatten()
is used to "Flatten a 2D array structured API instance to a 1D array structure" - so you need a 2D array first, whichapi
isn't. Try instead:Gold. Works perfectly, thanks!