乐闻世界logo
搜索文章和话题

How to convert a string to number in typescript

5 个月前提问
3 个月前修改
浏览次数49

6个答案

1
2
3
4
5
6

在TypeScript中,将字符串转换为数字通常有两种常用的方法:使用全局的 parseInt()parseFloat() 函数,以及使用一元加号运算符。下面是具体的例子:

使用 parseInt()parseFloat()

parseInt() 函数用于将字符串解析为整数,而 parseFloat() 函数则用于解析为浮点数。

typescript
let stringValue: string = "123"; let intValue: number = parseInt(stringValue); // 如果字符串是浮点数表示,可以使用parseFloat来获取浮点数 stringValue = "123.456"; let floatValue: number = parseFloat(stringValue); console.log(intValue); // 输出:123 console.log(floatValue); // 输出:123.456

parseInt() 函数可以接受第二个参数作为基数,以便解析不同进制的数字字符串。例如,如果你想解析十六进制的字符串,可以这样做:

typescript
stringValue = "0xF"; intValue = parseInt(stringValue, 16); console.log(intValue); // 输出:15

使用一元加号运算符

一元加号运算符(+)可以将其紧随的字符串转换成数字:

typescript
stringValue = "123"; intValue = +stringValue; // 一元加号 stringValue = "123.456"; floatValue = +stringValue; // 也能够处理浮点数 console.log(intValue); // 输出:123 console.log(floatValue); // 输出:123.456

这种方法很简洁,但是如果字符串不是合法的数字,则会得到 NaN(Not-a-Number)。

错误处理

在实际应用中,你通常需要处理可能发生的错误。例如,如果字符串不包含有效的数字,parseInt()parseFloat() 会返回 NaN,而一元加号运算符也是如此。你可能需要在转换后检查结果是否为 NaN,并相应地处理:

typescript
stringValue = "abc"; intValue = parseInt(stringValue); if (isNaN(intValue)) { console.log("parseInt 失败,字符串不包含有效数字"); } else { console.log(intValue); } // 使用一元加号运算符时的检查 floatValue = +stringValue; if (isNaN(floatValue)) { console.log("一元加号运算符转换失败,字符串不包含有效数字"); } else { console.log(floatValue); }

在编写TypeScript代码时,考虑到类型安全和错误处理是非常重要的,以上例子都演示了如何将字符串安全地转换为数字,并如何处理潜在的错误。

2024年6月29日 12:07 回复

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

shell
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).

Conversion table

Table taken from this answer

2024年6月29日 12:07 回复

For our fellow Angular users:

Within a template, Number(x) and parseInt(x) throws an error, and +x has no effect. Valid casting will be x*1 or x/1.

2024年6月29日 12:07 回复

As shown by other answers here, there are multiple ways to do the conversion:

shell
Number('123'); +'123'; parseInt('123'); parseFloat('123.45')

I'd like to mention one more thing on parseInt though.

When using parseInt, it makes sense to always pass the radix parameter. For decimal conversion, that is 10. This is the default value for the parameter, which is why it can be omitted. For binary, it's a 2 and 16 for hexadecimal. Actually, any radix between and including 2 and 36 works.

shell
parseInt('123') // 123 (don't do this) parseInt('123', 10) // 123 (much better) parseInt('1101', 2) // 13 parseInt('0xfae3', 16) // 64227

In some JS implementations, parseInt parses leading zeros as octal:

Although discouraged by ECMAScript 3 and forbidden by ECMAScript 5, many implementations interpret a numeric string beginning with a leading 0 as octal. The following may have an octal result, or it may have a decimal result. Always specify a radix to avoid this unreliable behavior.

MDN

The fact that code gets clearer is a nice side effect of specifying the radix parameter.

Since parseFloat only parses numeric expressions in radix 10, there's no need for a radix parameter here.

More on this:

2024年6月29日 12:07 回复

Expounding on what Ryan said, TypeScript embraces the JavaScript idioms in general.

shell
var n = +"1"; // the unary + converts to number var b = !!"2"; // the !! converts truthy to true, and falsy to false var s = ""+3; // the ""+ converts to string via toString()

All the interesting in-depth details at JavaScript Type Conversion.

2024年6月29日 12:07 回复

你的答案