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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42666343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:20:30  来源:igfitidea点击:

typescript - convert string to number

javascripttypescriptcasting

提问by john

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

My totalbalancetempis returning undefined whereas this.balanceis equal to 34 and this.pastAmountis equal to 23.

Mytotalbalancetemp返回 undefined 而this.balance等于 34this.pastAmount等于 23。

I have this in controller and displaying totalbalancetempusing exp in html

我在控制器中有这个并totalbalancetemp在 html 中使用 exp显示

回答by Mr. Polywhirl

Supply the proper type.

提供正确的类型。

let totalbalancetemp:number = balance + pastAmount

This will throw an error, because you are now guaranteeing that totalbalancetempwill 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)

回答by Senthil Kumar

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 - 定义变量(或)任何类型

回答by xird

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

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

回答by gildniy

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

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