search
HomeWeb Front-endJS TutorialHow to convert string to number in TypeScript?

如何在 TypeScript 中将字符串转换为数字?

Strings and numbers are primitive data types in TypeScript. Sometimes, we get a number in string format and we need to convert the string value to a number to perform mathematical operations on the value. If we perform mathematical operations on string values, it gives strange results. For example, adding another numeric value to a numeric string appends the numbers to the string rather than adding them.

We will learn to use various methods and approaches in TypeScript to convert strings into numeric values.

So, we need to convert string to number in TypeScript.

Use the " " unary operator

Unary operators take a single operand. It converts the operands into numeric values ​​before evaluating them. So we can use it to convert string to numeric value.

grammar

Users can follow the following syntax to convert strings into numeric values.

let numberValue: number = +stringNmber;

In the above syntax, we use the stringNumber variable as the operand of the unary " " operator.

Example

In this example, the stringNumber variable contains a numeric value in string format. After that, we convert the stringNumber string value into a number using the unary ‘ ‘ operator and store the calculated value in the numberValue variable.

In the output, the user can observe that the type of numberValue variable is number.

let stringNmber: string = "124354656";
let numberValue: number = +stringNmber;

console.log("The type of numberValue variable is " + typeof numberValue);
console.log("The value of the numberValue variable is " + numberValue);

When compiled, it will generate the following JavaScript code -

var stringNmber = "124354656";
var numberValue = +stringNmber;

console.log("The type of numberValue variable is " + typeof numberValue);
console.log("The value of the numberValue variable is " + numberValue);

Output

The above code will produce the following output -

The type of numberValue variable is number
The value of the numberValue variable is 124354656

Use Number() constructor

Number is an object in TypeScript, and we can use it as a constructor to create instances of Number objects.

We can pass a numeric value as Nuber() constructor parameter in numeric or string format.

grammar

Users can use the Number() constructor according to the following syntax to convert a string into a numeric value.

let num: number = Number(str);

In the above syntax, we pass the number value in string format as the parameter of the Number() constructor.

Example

In this example, we created string1 and string2 variables, which contain numeric values ​​in string format. After that, we convert these two variables into numbers using Number() constructor and store them in number1 and number2 variables.

After converting a string value to a number, the user can observe its type in the output.

let string1: string = "35161";
let string2: string = "65986132302";

let number1: number = Number(string1);
let number2: number = Number(string2);

console.log("The value of number1 is " + number1);
console.log("The type of number1 is " + typeof number1);

console.log("The value of number2 is " + number2);
console.log("The type of number2 is " + typeof number2);

When compiled, it will generate the following JavaScript code -

var string1 = "35161";
var string2 = "65986132302";
var number1 = Number(string1);
var number2 = Number(string2);

console.log("The value of number1 is " + number1);
console.log("The type of number1 is " + typeof number1);
console.log("The value of number2 is " + number2);
console.log("The type of number2 is " + typeof number2);

Output

The above code will produce the following output -

The value of number1 is 35161
The type of number1 is number

The value of number2 is 65986132302
The type of number2 is number

Use parseInt() method

TypeScript's parseInt() method extracts an integer value from a number string or the number itself, and removes the decimal part of the number.

grammar

Users can use the parseInt() method in TypeScript to convert strings to numbers according to the following syntax.

let num: number = parseInt(str);

In the above syntax, we pass the numeric value in string format as parseInt() method parameter.

Example

In the following example, the convertNumToString() function converts a string to a number and returns a numeric value. In the function, we have used the parseInt() method to extract the number from the string.

We call the convertNumToString() function twice by passing different numbers in string format as parameters and the user can observe the converted numeric value in the output.

let stringNumber: string = "12234567998";
let stringNumber2: string = "34345465.4333";

function convertNumToString(str: string) {
  let num: number = parseInt(str);
  return num;
}

console.log(
  "After converting the " +
    stringNumber +
    " to number value is " +
    convertNumToString(stringNumber)
);

console.log(
  "After converting the " +
    stringNumber2 +
    " to number value is " +
    convertNumToString(stringNumber2)
);

When compiled, it will generate the following JavaScript code -

var stringNumber = "12234567998";
var stringNumber2 = "34345465.4333";
function convertNumToString(str) {
   var num = parseInt(str);
   return num;
}
console.log("After converting the " +
   stringNumber +
   " to number value is " +
   convertNumToString(stringNumber));
console.log("After converting the " +
   stringNumber2 +
   " to number value is " +
   convertNumToString(stringNumber2));

Output

The above code will produce the following output -

After converting the 12234567998 to number value is 12234567998
After converting the 34345465.4333 to number value is 34345465

Use parseFlot() method

The parseFloat() method performs the same job as the parseInt() method, converting a string to a number. The only difference is that it does not remove the values ​​after the decimal point, which means it extracts floating point values ​​from strings, while parseInt() method extracts integer values ​​from strings.

grammar

Users can use the parseFloat() method according to the following syntax to convert strings to numbers.

let numberValue: number = parseFloat(stringValue);

In the above syntax, stringValue is a floating point number in string format.

Example

In the following example, the stringToFloat() function demonstrates how to use the parseFloat() method to extract a floating point value from a given string. We have called the stringToFloat() function three times.

On the third call to the stringToFloat() function, we pass it a string with numbers and other characters as parameters. In the output, we can see that it removes characters from the string and extracts only floating point values.

let strFloat: string = "34356757";
let strFloat2: string = "7867.465546";

function stringToFloat(stringValue: string) {
  let numberValue: number = parseFloat(stringValue);
  console.log(
    "The " +
      stringValue +
      " value after converting to the number is " +
      numberValue
  );
}

stringToFloat(strFloat);
stringToFloat(strFloat2);
stringToFloat("232343.43434fd");

When compiled, it will generate the following JavaScript code -

var strFloat = "34356757";
var strFloat2 = "7867.465546";
function stringToFloat(stringValue) {
    var numberValue = parseFloat(stringValue);
    console.log("The " +
        stringValue +
        " value after converting to the number is " +
        numberValue);
}
stringToFloat(strFloat);
stringToFloat(strFloat2);
stringToFloat("232343.43434fd");

Output

The above code will produce the following output -

The 34356757 value after converting to the number is 34356757
The 7867.465546 value after converting to the number is 7867.465546
The 232343.43434fd value after converting to the number is 232343.43434

In this tutorial, the user learned four ways to convert a numeric value given in string format into an actual number. The best way to convert a string to a number is to use unary operators, which are less time consuming than other operators. However, users can also use the Number() constructor.

The above is the detailed content of How to convert string to number in TypeScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

jQuery Check if Date is ValidjQuery Check if Date is ValidMar 01, 2025 am 08:51 AM

Simple JavaScript functions are used to check if a date is valid. function isValidDate(s) { var bits = s.split('/'); var d = new Date(bits[2] '/' bits[1] '/' bits[0]); return !!(d && (d.getMonth() 1) == bits[1] && d.getDate() == Number(bits[0])); } //test var

jQuery get element padding/marginjQuery get element padding/marginMar 01, 2025 am 08:53 AM

This article discusses how to use jQuery to obtain and set the inner margin and margin values ​​of DOM elements, especially the specific locations of the outer margin and inner margins of the element. While it is possible to set the inner and outer margins of an element using CSS, getting accurate values ​​can be tricky. // set up $("div.header").css("margin","10px"); $("div.header").css("padding","10px"); You might think this code is

10 jQuery Accordions Tabs10 jQuery Accordions TabsMar 01, 2025 am 01:34 AM

This article explores ten exceptional jQuery tabs and accordions. The key difference between tabs and accordions lies in how their content panels are displayed and hidden. Let's delve into these ten examples. Related articles: 10 jQuery Tab Plugins

10 Worth Checking Out jQuery Plugins10 Worth Checking Out jQuery PluginsMar 01, 2025 am 01:29 AM

Discover ten exceptional jQuery plugins to elevate your website's dynamism and visual appeal! This curated collection offers diverse functionalities, from image animation to interactive galleries. Let's explore these powerful tools: Related Posts: 1

HTTP Debugging with Node and http-consoleHTTP Debugging with Node and http-consoleMar 01, 2025 am 01:37 AM

http-console is a Node module that gives you a command-line interface for executing HTTP commands. It’s great for debugging and seeing exactly what is going on with your HTTP requests, regardless of whether they’re made against a web server, web serv

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

jquery add scrollbar to divjquery add scrollbar to divMar 01, 2025 am 01:30 AM

The following jQuery code snippet can be used to add scrollbars when the div content exceeds the container element area. (No demonstration, please copy it directly to Firebug) //D = document //W = window //$ = jQuery var contentArea = $(this), wintop = contentArea.scrollTop(), docheight = $(D).height(), winheight = $(W).height(), divheight = $('#c

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.