1

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

Bartosz Gościński
  • 1,468
  • 1
  • 16
  • 28
Morgan Ng
  • 813
  • 2
  • 10
  • 22

5 Answers5

1

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);
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Just round the decimal's:

Math.round();
Lulceltech
  • 1,662
  • 11
  • 22
0

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.

Mykola Borysyuk
  • 3,373
  • 1
  • 18
  • 24
0

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
Mohammad Kermani
  • 5,188
  • 7
  • 37
  • 61
0

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));
Karan Dhir
  • 731
  • 1
  • 6
  • 24