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

How to convert a string to a number in TypeScript?

1个答案

1

In TypeScript, converting strings to numbers typically involves several common methods. This section introduces several common methods with examples:

1. Using the Number Constructor

This is one of the most straightforward methods and is suitable for most cases. If the string is not a valid number, it returns NaN.

typescript
let str = "123"; let num = Number(str); console.log(num); // Output: 123

2. Using the Unary Plus Operator

This method is concise and commonly used, as it directly converts the string to a number.

typescript
let str = "456"; let num = +str; console.log(num); // Output: 456

3. Using parseInt() or parseFloat()

These functions are very useful when parsing integers or floating-point numbers from a string. parseInt() is used for integers without decimals, while parseFloat() is used for numbers with decimals.

typescript
let strInt = "789px"; let strFloat = "3.14someText"; let numInt = parseInt(strInt); let numFloat = parseFloat(strFloat); console.log(numInt); // Output: 789 console.log(numFloat); // Output: 3.14
  • When you are certain that the entire string represents a number and you need a numeric value, use Number() or the unary plus operator.
  • If the string contains non-numeric characters but you only need the numeric part (e.g., 123px converted to 123), use parseInt() or parseFloat().

By using these methods, you can flexibly choose the appropriate string-to-number conversion method based on your specific requirements.

2024年7月29日 13:38 回复

你的答案