0

Here is my code where I am implementing a simple calculator in TypeScript .The problem here is that all the operations are working fine except addition where instead of addition, concatenation of numbers is performed.

HTML CODE :

<input type="text" [(ngModel)]="n1" />
 <input type="text" [(ngModel)]="n2" />

<h1>Number 1 : {{n1}}</h1>
<h1>Number 2 : {{n2}}</h1>

<select (change)="handle(selectField.value);" #selectField>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multiply">Multiplication</option>
<option value="divide">Division</option>

</select>


<h1>Result = {{result}}</h1>  

My Angular Code is as follows:

import {
  Component,
  OnInit
} from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {

  n1: number = 0;
  n2: number = 0;
  result: number = 0;

  handle(value: string) {

    if (value == "addition") {
      this.result = this.n1 + this.n2;
    } else if (value == "subtraction") {
      this.result = this.n1 - this.n2;
    } else if (value == "multiply") {
      this.result = this.n1 * this.n2;
    } else if (value == "divide") {
      this.result = this.n1 / this.n2;
    }

  }

  constructor() {}
  ngOnInit() {

  }

}

I have declared both n1 and n2 as numbers and also the result as number. So why is it that the numbers are being treated as strings instead of integers?

Note: I have gone through some other Stack Overflow posts on similar issue but couldn't find the possible solution.

Please help!

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
Sai Raman Kilambi
  • 878
  • 2
  • 12
  • 29

2 Answers2

2

You can resolve it. this.result=(+this.n1)+(+this.n2);

aimprogman
  • 294
  • 2
  • 3
  • 16
  • 4
    While this code snippet may solve the question, [including an explanation](//meta.stackexchange.com/questions/114762/explaining-entirely-code-based-answers) really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! – Heretic Monkey Jun 21 '17 at 16:11
1

Any value from an HTML input is automatically string. To resolve this, you must cast/convert your input value to a number. The (+this.n1) hack does it, but to really do it right you should cast or convert your values.

this.result = parseInt(this.n1) + parseInt(this.n2);

This is just one way. There are several others.

MBielski
  • 6,628
  • 3
  • 32
  • 43
  • 1
    I should also note that this method is prone to failures if the value from the input evaluates to NAN. – MBielski Jun 21 '17 at 16:16