I have an object that has a money property with the datatype Decimal(10,2) on mySql.
My javascript makes an http reques to retrieve those values and I process the data inside my javascript function to add up all the values into one $scope:
$scope.expected = 0;
for(var k = 0; k < collection.length; k++)
{
$scope.expected += Number(collection[k].price);
}
price
is the money value that contains 125.89
as the value from the DB. The iteration makes 31 iterations as collection.length
returns me 31
.
I used the Number
Reference because it starts out as a string.
When The looping finishes, I end up with this sum: 3902.589999999999
But all I want is 3902.58
since this is money and it must be an exact representation. I researched around and the community seems to agree on using toFixed(2)
but from my understanding, toFixed(2)
rounds the number up which is something I do NOT want to do since this operation involves cash.
Is there a way to keep the 2 decimal places without rounding?
I also kept a log of the console.log throughout the entire loop. Here is the result:
125.89
251.78
377.67
503.56
629.45
755.34
881.23
1007.12
1133.01
1258.9
1384.7900000000002
1510.6800000000003
1636.5700000000004
1762.4600000000005
1888.3500000000006
2014.2400000000007
2140.1300000000006
2266.0200000000004
2391.9100000000003
2517.8
2643.69
2769.58
2895.47
3021.3599999999997
3147.2499999999995
3273.1399999999994
3399.0299999999993
3524.919999999999
3650.809999999999
3776.699999999999
3902.589999999999