john
john

Reputation: 21

typescript - convert string to number

totalbalancetemp = (Number(this.balance)) + (Number(this.pastAmount));

My totalbalancetemp is returning undefined whereas this.balance is equal to 34 and this.pastAmount is equal to 23.

I have this in controller and displaying totalbalancetemp using exp in html

Upvotes: 2

Views: 40551

Answers (5)

Alireza Ebrahimkhani
Alireza Ebrahimkhani

Reputation: 551

totalbalancetemp = (Number(this.balance)) + (Number(this.pastAmount));

please try this it should work

totalbalancetemp:number = (+this.balance) + (+this.pastAmount);

Upvotes: 2

gildniy
gildniy

Reputation: 3943

Do a +this.balance in the .ts file or this.balance*1 or this.balance/1 on in the template file.

Upvotes: 0

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48751

Supply the proper type.

let totalbalancetemp:number = balance + pastAmount

This will throw an error, because you are now guaranteeing that totalbalancetemp will be a number.

The type String is not assignable to type 'number'

Try the following:

let balance:string = '34',
    pastAmount:string = '23',
    totalbalancetemp:number = 0

totalbalancetemp = Number(balance) + Number(pastAmount)

alert(totalbalancetemp)

Upvotes: 2

xird
xird

Reputation: 785

totalbalancetemp should be replaced by this.totalbalancetemp if it's part of the angular 2 component

Upvotes: 0

Senthil Kumar
Senthil Kumar

Reputation: 592

var totalbalancetemp = null; this.balance = 34; this.pastAmount = 23; 

totalbalancetemp = (Number(this.balance)) + (Number(this.pastAmount));

alert(totalbalancetemp);

-->totalbalancetemp - Define Variable (or) any type

Upvotes: 0

Related Questions