What are the ways to convert strings to numbers in Typescript?

In TypeScript, there are several ways to convert a string to a numeric value (i.e. string to number type conversion). The following are some common methods:
1. Use the global functions parseFloat() and parseInt():

const strNumber = "123.45";
const parsedFloat = parseFloat(strNumber); // 将字符串转换为浮点数
const parsedInt = parseInt(strNumber, 10); // 将字符串转换为整数(以十进制解析)

2. Use the Number constructor:

const strNumber = "123.45";
const parsedNumber = Number(strNumber); // 将字符串转换为数值(整数或浮点数)

3. Use template literals and + operator:

const strNumber = "123.45";
const convertedNumber = +strNumber; // 将字符串转换为数值

4. Use the functional form of parseInt() and parseFloat() methods:

function parseNumber(input: string): number {
    
    
  return parseFloat(input); // 或者使用 parseInt(input, 10)
}

const strNumber = "123.45";
const parsedValue = parseNumber(strNumber); // 将字符串转换为数值

It should be noted that these methods will convert to integers or floating point numbers according to the content of the string during conversion. If the string cannot be correctly parsed into a numerical value, NaN (Not-a-Number) will be returned. When using parseInt(), it is recommended to always specify base arguments, for example, use parseInt(input, 10) to ensure decimal parsing.

Remember that in actual applications, appropriate error handling is required for user-entered strings to prevent invalid conversions from causing unexpected errors.

Guess you like

Origin blog.csdn.net/weixin_43160662/article/details/132331008