Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
344 views
in Technique[技术] by (71.8m points)

typescript - TypeScript将字符串转换为数字(TypeScript Converting a String to a number)

Anyone a suggestion on how to convert a string to a number in TypeScript?

(有人建议如何将字符串转换为TypeScript中的数字?)

var aNumber : number = "1"; // --> Error

// Could this be done?
var defaultValue = 0;
var aNumber : number = "1".toInt32(defaultValue);

// Or ..
var defaultValue = 0;
var aNumber : number = StringToInt("1", defaultValue);

Update: I did some extra puzzling, the best sofar I've come up with: var aNumber : number = ( "1") * 1;

(更新:我做了一些额外的困惑,我想出的最好的音乐:var aNumber:number =(“1”)* 1;)

checking if a string is numeric is answered here: In Typescript, How to check if a string is Numeric .

(检查字符串是否为数字在此处回答: 在Typescript中,如何检查字符串是否为数字 。)

  ask by Paul0515 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use the parseInt or parseFloat functions, or simply use the unary + operator:

(您可以使用parseIntparseFloat函数,或者只使用一元+运算符:)

var x = "32";
var y = +x; // y: number

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...