0

I am trying to get the sum of 4 values using Javascript and the Angular framework. Everything is working fine for the most part except that in some very specific cases, the result is off.

This is what i'm doing

var grandTotal = Number($scope.Quote.BundlePrice) + Number($scope.Quote.InstallationFees) + Number($scope.Quote.ShippingFees) + Number($scope.Quote.Taxes);
$scope.Quote.GrandTotal = grandTotal

If I use these values

BundlePrice = "50.01"
InstallationFees = "20"
ShippingFees = "10"
Taxes = "11.99"

The Grand Total value I get on my webpage is 91.99999999999999 when it should be 92

I did a console log of the strings i'm trying to parse and everything seems to be fine there as well, this is what i'm getting. Values are in order.

50.01 and 20 and 10 and 11.99

Any hints on what could possible be causing this problem? I've tried using parseFloat, still didn't work. I tried to add toFixed(2) at the end as well but the same problem is happening and I can't seem to find anyone having the same problem as me.

Thank you!

Raphy963
  • 38
  • 4
  • Take a look at this: https://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Piyin Nov 17 '17 at 16:22
  • Oh wow, I never saw this page even after my search. Thanks alot! – Raphy963 Nov 17 '17 at 16:23
  • Javascript is known to have a rounding problem. So it is easiest to just round the number to the nearest hundredths place: `$scope.Quote.GrandTotal = grandTotal.toFixed(2);` – Intervalia Nov 17 '17 at 16:30
  • This seems to always work since whenever it's off it's always .999999. Your fix worked, I thought this was going to strip the number to only have 2 digits, but I guess I was wrong. – Raphy963 Nov 17 '17 at 16:33

0 Answers0