1

I wrote a component like below:

export class AppComponent {
    public num1: number = 2;
    public num2: number = 3;
    public sum: number = 0;
    public add() {
        this.sum = this.num1 + this.num2;
    }
}

For this, I'm getting sum as 23 instead of 5. Give me a proper solution to do addition. I will be glad to know the answer

  • I don't see any problems here: http://plnkr.co/edit/ZE9MuIQKQaUUc39ptJ5u?p=preview – eko Nov 11 '16 at 09:55
  • See Nitzan Tomer's answer for why your TypeScript variables declared as numbers can be treated as strings: https://stackoverflow.com/questions/39269701/typescript-trying-the-addition-of-two-variables-but-get-the-concatenation-of-t – Ralph Oct 04 '17 at 22:02

1 Answers1

5

this is because your numbers are being treated as strings.

so its doing "2" + "3" = "23"

to force a number use parseInt function or do ...

this.sum = +this.num1 + +this.num2;

or this should work too ...

this.sum = +this.num1 + this.num2;
danday74
  • 52,471
  • 49
  • 232
  • 283