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.
typescriptlet 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.
typescriptlet 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.
typescriptlet 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.,
123pxconverted to123), useparseInt()orparseFloat().
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 回复