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

How to convert a string to number in typescript

1个答案

1

In TypeScript, converting strings to numbers typically involves two common methods: using the parseInt() and parseFloat() functions, and using the unary plus operator. Below are specific examples:

Using parseInt() and parseFloat()

The parseInt() function parses a string into an integer, while parseFloat() parses it into a floating-point number.

typescript
let stringValue: string = "123"; let intValue: number = parseInt(stringValue); // For floating-point strings, use `parseFloat` to obtain the floating-point value stringValue = "123.456"; let floatValue: number = parseFloat(stringValue); console.log(intValue); // Output: 123 console.log(floatValue); // Output: 123.456

The parseInt() function accepts a second parameter as the radix for parsing numbers in different bases. For example, to parse a hexadecimal string:

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

Using the unary plus operator

The unary plus operator (+) converts the immediately following string into a number:

typescript
stringValue = "123"; intValue = +stringValue; // Unary plus stringValue = "123.456"; floatValue = +stringValue; // Handles floating-point numbers console.log(intValue); // Output: 123 console.log(floatValue); // Output: 123.456

This method is concise, but if the string is not a valid number, it results in NaN (Not-a-Number).

Error Handling

In practical applications, you often need to handle potential errors. For instance, if the string lacks valid numbers, both parseInt() and parseFloat() return NaN, and the unary plus operator does the same. You may need to check if the result is NaN after conversion and handle it accordingly:

typescript
stringValue = "abc"; intValue = parseInt(stringValue); if (isNaN(intValue)) { console.log("parseInt failed: string contains no valid numbers"); } else { console.log(intValue); } // When checking with the unary plus operator floatValue = +stringValue; if (isNaN(floatValue)) { console.log("Unary plus conversion failed: string contains no valid numbers"); } else { console.log(floatValue); }

When writing TypeScript code, considering type safety and error handling is crucial. The examples above demonstrate how to safely convert strings to numbers and handle potential errors.

2024年6月29日 12:07 回复

你的答案