typescript - convert string to number

32,685

Solution 1

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)

Solution 2

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

please try this it should work

totalbalancetemp:number = (+this.balance) + (+this.pastAmount);
Share:
32,685
john
Author by

john

Updated on July 09, 2022

Comments

  • john
    john almost 2 years
    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