0

I am trying to do maths and i been getting values such as 200052 i.e if i add 2000+52, where it should be 2052. What am i doing wrong or missing something?

//get value of amount eneterd
 amount = document.getElementById("amount").value;
 //apply percentage
 if(rateExcel.checked = true){
    total= parseINT((amount/100) * 5);
    total= total + parseINT(amount);
//still i get the same, like 20052 instead of 252.
 };

Edit: The input is integer, not a string! I see many people trying to be ninja about telling to use parseINT(), but i tried and it didn't work.

localhost
  • 822
  • 2
  • 20
  • 51
  • amount is getting a string value, so if a string is appended in your logic which makes the whole thing a string, use parseInt(amount) or Number(amount) – Newinjava Jun 30 '15 at 09:31
  • As an aside, the line `if(rateExcel.checked = true)` is not doing what you think it is. That's checking the result of an assignment operation (single equals sign) and will always be truthy in this case. – serg10 Jun 30 '15 at 09:32
  • @serg10 so == to check is the radio button is checked? – localhost Jun 30 '15 at 09:33
  • 1
    @Nofel, no, just `if (rateExcel.checked)` - there's no need for a comparison against `true` when you already have a boolean value. – Alnitak Jun 30 '15 at 09:34
  • 1
    @Nofel you should favour '===' in general, but in this case you'd probably be fine with just `if(rateExcel.checked)`. – serg10 Jun 30 '15 at 09:34
  • If you have that kind of trouble, you'll also probably have floating point precision errors at some point, which [this post](http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript) might help to solve, when you'll have it :-) – Laurent S. Jun 30 '15 at 09:35
  • @serg10 he wouldn't be merely "just fine", omitting the '===' should be the canonical way of writing this! – Alnitak Jun 30 '15 at 09:40

3 Answers3

1

You fix this by forcing the amount variable to become an int since it's probably received as a string.:

total = total + parseInt(amount);
Niddro
  • 1,705
  • 2
  • 12
  • 24
0

Your amount is a string so you need to convert your amount to number using

total= total + Number(amount);
bugwheels94
  • 30,681
  • 3
  • 39
  • 60
0
//get value of amount eneterd
 amount = document.getElementById("amount").value;
 //apply percentage
 if(rateExcel.checked == true){
    total= (parseInt(amount,10)/100) * 5;
    total= total + parseInt(amount,10);
 };
AkshayJ
  • 771
  • 6
  • 15