简体   繁体   English

打字稿 - 将字符串转换为数字

[英]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.我的totalbalancetemp返回 undefined 而this.balance等于 34 而this.pastAmount等于 23。

I have this in controller and displaying totalbalancetemp using exp in html我在控制器中有这个,并在 html 中使用 exp 显示totalbalancetemp

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 .这将引发错误,因为您现在保证totalbalancetemp将是一个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)

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

请试试这个它应该可以工作

totalbalancetemp:number = (+this.balance) + (+this.pastAmount);
var totalbalancetemp = null; this.balance = 34; this.pastAmount = 23; 

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

alert(totalbalancetemp);

-->totalbalancetemp - Define Variable (or) any type -->totalbalancetemp - 定义变量(或)任何类型

如果 totalbalancetemp 是 angular 2 组件的一部分,则应由 this.totalbalancetemp 替换

在 .ts 文件中执行+this.balance或在模板文件中执行this.balance*1this.balance/1 on。

In typescript, we can convert the string in different ways.在打字稿中,我们可以用不同的方式转换字符串。 Here's the below methods for converting the string to number这是将string转换为number的以下方法

x = parseInt('34')

OR或者

x = Number('34')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM