简体   繁体   中英

How do I sum total amount of array in loop?

How would I sum the total of amount that is returned in array by using Ajax?

Is there other way to calculate the sum with amount of .000 behind?

Example:

 for (i = 0; i < data.RecordCount; i++) {

 totalBetAmount += parseFloat(data.Records[i].betAmount);

Result: 0.22130000001

只是围绕小数点:

Math.round();

Try like this.

//this will be total sum of all numbers
var totalSum = (data.Records || []).reduce(function(total, num){
    return parseFloat(total) + parseFloat(num);
});
//now you can do what you want using ParseInt or toFixed...

//convert to INT
totalSum = parseInt(totalSum);

//leave just 2 numbers after decimal like 1.12
totalSum = totalSum.toFixed(2);

Hope this helps.

If you use ES6 ( ECMAScript 2015 ), you can use the reduce function (Great video tutorial to learn the reduce)

Here is a simple example:

 var yourArray = [50, 60, 70, 100, 20] var sum = yourArray.reduce((a, b) => a + b, 0); console.log(sum); //Returns: 300 

This inaccuracies result from the fact that many numbers do not have an exact representation in floating point , which is what JavaScript uses to store numbers.

A pragmatic solution is to round your result to a certain number of decimals after the decimal point, like so:

totalBetAmount = Math.round(totalBetAmount*100000000)/100000000;

Here is a snippet that shows the original number and the rounded number:

 // Sample data var data = { Records: [ { betAmount: 0.0001 }, { betAmount: 0.0001 }, { betAmount: 0.0001 }, ], RecordCount: 3 }; var totalBetAmount = 0; for (i = 0; i < data.RecordCount; i++) { totalBetAmount += parseFloat(data.Records[i].betAmount); } console.log('before:', totalBetAmount); // round of inaccuracies, assuming decimals totalBetAmount = Math.round(totalBetAmount*100000000)/100000000; console.log('after:', totalBetAmount); 

I'm not familiar with Ajax but this might be helpul :

var arr = [5.33655,6.6655,9.554];
var sum = 0;
for (var i = 0 ; i < arr.length ; i++) {
  sum += arr[i] 
};
console.log(sum.toFixed(3));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM