如何在 TypeScript 中将字符串转换为数字? [英] How to convert a string to number in TypeScript?

查看:88
本文介绍了如何在 TypeScript 中将字符串转换为数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个数字的字符串表示,如何在 TypeScript 中将其转换为 number 类型?

var numberString: string = "1234";var numberValue: number =/* 我应该如何处理 `numberString`?*/;

解决方案

表格取自 这个答案

Given a string representation of a number, how can I convert it to number type in TypeScript?

var numberString: string = "1234";
var numberValue: number = /* what should I do with `numberString`? */;

解决方案

Exactly like in JavaScript, you can use the parseInt or parseFloat functions, or simply use the unary + operator:

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

All of the mentioned techniques will have correct typing and will correctly parse simple decimal integer strings like "123", but will behave differently for various other, possibly expected, cases (like "123.45") and corner cases (like null).

Table taken from this answer

这篇关于如何在 TypeScript 中将字符串转换为数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆