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

2

1 Answer 1

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;
Sign up to request clarification or add additional context in comments.

3 Comments

According to the question, they aren't strings.
The question has most likely not the full code. I would expect the same reason that's provided in the answer.
isNaN("2") === false

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.