-1

i want to add 3 prices like 18+10+5 but it is returning answer as 18105 instead of 33.as shown in code totalPrice, extraFoodPrice, extraNonFoodPrice are number type.

finalAmount() {
return this.totalPrice + this.extraFoodPrice + this.extraNonFoodPrice;
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
  • may be those variables type is string. if those are string use this https://stackoverflow.com/questions/14667713/typescript-converting-a-string-to-a-number – Rahul Raveendran Aug 14 '19 at 09:21
  • `return parseInt(this.totalPrice) + parseInt(this.extraFoodPrice) + parseInt(this.extraNonFoodPrice)`; – Atishay Jain Aug 14 '19 at 09:24

4 Answers4

0

Probably variables are strings. Try adding an extra + before each variable to convert to number, or use parseInt.

Hope it helps.

Paulo Pereira
  • 211
  • 1
  • 8
0

Apparently, they are strings. Check the code which could affect those, possibly change it into strings and fix those problems. Sharing the code here could be helpful as well.

igor_c
  • 1,200
  • 1
  • 8
  • 20
0

At least totalPrice and/or extraFoodPrice is a string and not a number. You probably get this value from an <input> field in your code. You should parse it to number first:

finalAmount() {
  return (+this.totalPrice || 0) + (+this.extraFoodPrice || 0) + (+this.extraNonFoodPrice || 0);
}
Poul Kruijt
  • 69,713
  • 12
  • 145
  • 149
0

It seems you are adding strings.

Try to explicitely convert the values to numbers with parseFloat for example.

Exact syntax and details here : https://gomakethings.com/converting-strings-to-numbers-with-vanilla-javascript/

hth