Morgan Ng
Morgan Ng

Reputation: 813

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

Upvotes: 1

Views: 620

Answers (5)

trincot
trincot

Reputation: 349946

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);

Upvotes: 1

Karan Singh Dhir
Karan Singh Dhir

Reputation: 751

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));

Upvotes: 0

Mohammad Kermani
Mohammad Kermani

Reputation: 5396

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

Upvotes: 0

Mykola Borysyuk
Mykola Borysyuk

Reputation: 3411

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.

Upvotes: 0

Lulceltech
Lulceltech

Reputation: 1702

Just round the decimal's:

Math.round();

Upvotes: 0

Related Questions