How To Convert String To Number In JavaScript

String and number are two important data types in JavaScript that are widely used in programming. Strings are character sequences surrounded by quotes (either single or double quotes).

In contrast, numbers are used to represent numerical values like integers, floating-point numbers, and scientific notation.

A common task in JavaScript programming is converting a string to a number. In this blog, we’ll look at some approaches on how to convert string to number in javascript.

Why Is There A Need to convert string to number in javascript

How to change string to number in javascript is required for a variety of reasons. Among the primary reasons are:

  • User Input:- It is common to receive data in the form of a string when dealing with user input. To perform mathematical calculations or comparisons, this data must be converted to a number.
  • Data Processing:- Data may occasionally need to be handled as numeric values even though it is stored in a textual format.
  • Validation:- It may be necessary to validate that the data is a numeric value in order to ensure that it is entered correctly and accurately.
  • Formatting:- Numeric values may need to be formatted a certain way while being shown on a webpage or in a user interface.

How to convert string to number in javascript is an important aspect of working with data  and is required for performing mathematical calculations, comparisons, and other  operations that require numeric values.

Approaches to convert string to Number in JavaScript

Approaches to convert string to Number in JavaScript

There are four methods, how to convert string to number in javascript. Methods are listed below:-

  1. Using the function parseInt()
  2. Using the function parseFloat()
  3. Using the function Number()
  4. Making Use of the Unary Plus Operator

Let’s have a look.

1. Using the function parseInt()

In javascript, the parsInt() function is a built-in function that accepts two arguments: the string to be converted and the number system’s base (optional).

Source Code:-

const s = “123”;

//here we are using the function on str
const num = parseInt(s);

console.log(num);

Output:-

123

Explanation of code:-

  • We had a string in the variable “s”.
  • The parseInt() function is passed the input string “10” as an argument.
  • The function parseInt() converts the string to a number value and returns it.
  • The resulting integer value, in this case 10, is saved in the variable “num.”

2. Using the function parseFloat()

Another built-in function that can be used to change string to number in javascript is the parseFloat() function. The string to be converted is the only argument to this function. The floating-point representation of the input string is returned.

Source Code:-

const s = “3.14”;

//here we are using the function on str
const num = parseFloat(s);

console.log(num);

Output:-

3.14

Explanation of code:-

  • We had a string in the variable “s”.
  • The parseFloat() function is passed the input string “10” as an argument.
  • The function parseFloat() converts the string to a number value and returns it.
  • The resulting integer value, in this case 10, is saved in the variable “num.”

3. Using the function Number()

The Number() is a built-in function that is used to convert a string in an integer. The numeric representation of the input string is returned as the value.

Sample Code:-

let d = '42';
let e='42.5';
let f='4@45678';

//here we are using the function
let a = Number(d);
let b = Number(e);
let c = Number(f);

console.log(a);
console.log(b);
console.log(c);

Output:-

42
42.5
NaN

Explanation of code:-

  • The values for the string variables ‘d,’ ‘e,’ and ‘f’ are ’42,’ ‘42.5,’ and ‘4@45678’, respectively.
  • The Number() function is used to convert these string variables to integers, which are then stored in new variables ‘a’, ‘b’, and ‘c’.
  • String ’42’ can be converted to an integer, ‘a’ will be assigned the number 42.
  • String ‘42.5’ can be converted to a floating-point number, ‘b’ will be assigned the integer 42.5.
  • Because the string ‘4@45678’ cannot be converted to a valid number, ‘c’ will be assigned the special value NaN (Not a Number).
  • Finally, using console.log, the values ‘a’, ‘b’, and ‘c’ are logged to the console ().

4.Making Use of the Unary Plus Operator

To convert a string to a number, use the Unary Plus Operator (+). The string to be converted is the only argument to this operator. The numeric representation of the input string is returned as the value.

Sample Code:-

const s = “999”;

//here we are using the function
const num = +s;

console.log(num);
]\\

Output:-

999

Explanation of code:-

  • This code converts a string to a number using built-in Number() function.
  • The Number() function is given the string “3.14” as an argument.
  • Using JavaScript’s standard numeric conversion rules, the function converts the string to the number 3.14.
  • The result is then saved in the variable “num” for later use in the programme.

Best approach:- Using the function Number()

To convert a string to a number, use the Unary Plus Operator (+). Here are the reasons for same:

  • Flexibility:- The Number() function can accept a variety of input types, including integers, floating-point numbers, and even scientific notation. This makes code more adaptable and versatile than the rest of the  functions, which are limited to certain types of input.
  • Simplicity:- The Number() function is simple and easy to use. It takes only one argument (the input string) and outputs a number. As a result, it is a straightforward and concise solution to the string-to-number conversion problem.
  • Consistency:- All modern browsers and platforms support the Number() function, which is part of the core JavaScript language.

Sample Problem how to convert string to Number in JavaScript

Sample Problem 1:- Using the function parseInt()

Problem statement:- You’re creating a web application that requires users to fill out a form with their age. The age, on the other hand, is stored as a string and must be converted to a number before being stored in the database. How can the parseInt() function be used to convert a string to a number?

Solution:-

Solution Code:-

let ageStr = “30”;

//here we are using the function
let age = parseInt(ageStr);
console.log(age);

Output:-

30

Explanation:-

  • The string that has to be converted is saved in a variable called ageStr.
  • The ageStr argument is passed to the parseInt() function, which converts the string to a number.
  • The number 30 will be returned as the integer value contained in the ageStr variable after being converted to a number using parseInt ().
  • The resulting number is then saved in the variable age.
  • The console.log() function is used to display the age value on the console.

Sample Problem 2:- Using the function parseFloat()

Problem statement:- You’re creating a calculator app that requires users to fill out a form with decimal numbers. However, the numbers are stored as strings and must be converted to numbers before being used in calculations. How can the parseFloat() function be used to convert strings to numbers?

Solution:-

Solution Code:-

let numStr1 = “4.14”;
let numStr2 = “3.71”;
let num1 = parseFloat(numStr1);
let num2 = parseFloat(numStr2);
let sum = num1 + num2;
console.log(sum);

Output:-

7.85

Explanation:-

  • The two strings to be converted are kept in variables numStr1 and numStr2.
  • The parseFloat() function is invoked with the arguments numStr1 and numStr2, which convert the strings to numbers.
  • The resulting numbers are saved in variables num1 and num2.
  • The addition operator is used to compute the sum of num1 and num2 and stores the result in a variable called sum.
  • The console.log() function is used to display the sum value on the console.
  • The result is 7.85, which is the sum of the numbers stored in num1 and num2 after they were converted from strings using the parseFloat() function.

Sample Problem 3:- Using the function Number()

Problem statement:- Assume you’re creating a simple calculator application in JavaScript. You have a text input field where the user can enter numbers, but the results are returned as a string. To perform arithmetic operations, you must convert this string input to a number. What JavaScript function would you use for this, and how would you use it?

Solution:-

Solution Code:-

// This is HTML code:
<input type="text" id="num1">
<input type="text" id="num2">
<button onclick="calculate()">Calculate</button>

// From here JavaScript code Starts:
function calculate() {
  var num3 = document.getElementById("num1").value;
  var num4 = document.getElementById("num2").value;
  
  // Convert the string inputs to numbers using the Number() function
  num3 = Number(num3);
  num4 = Number(num4);
  
  // Perform arithmetic operations on the numbers
  var Sum = num3 + num4;
  var Difference = num3 - num4;
  var Product = num3 * num4;
  var Quotient = num3 / num4;
  
  // Display the results
  alert("Sum: " + Sum + "\nDifference: " + Difference + "\nProduct: " + Product + "\nQuotient: " + Quotient);
}

Input:- Give the input 10 and 5 to num1 and num2 respectively.

Output:-

Sum: 15
Difference: 5
Product: 50
Quotient: 2

Explanation:-

  • The provided code demonstrates how to use JavaScript to perform arithmetic operations on values entered into HTML input fields by users.
  • The given HTML code contains two input fields with the id’s “num1” and “num2,” and also contains a button with an “onclick” event that calls the function.
  • The ‘calculate()’ function in the JavaScript code gets the values from the “num1” and “num2” and stores them as strings in variables “num1” and “num2,” respectively. These strings are then converted to numbers using the Number() function and assigned back to the same variables to perform arithmetic operations.
  • The numbers are then subjected to arithmetic operations, with the results saved in variables “sum,” “difference,” “product,” and “quotient.”

Sample Problem 4:- Making Use of the Unary Plus Operator

Problem statement:- You’re creating a shopping cart app that requires users to enter the number of items they want to buy. However, the quantity is stored as a string and must be converted to a number before the total price can be calculated. How can the Unary Plus operator be used to convert a string to a number?

Solution:-

Solution Code:-

let quantity = “3”;
let price = 56.73;
let total = +quantity * price;
console.log(total);

Output:-

170.19

Explanation:-

  • The variable quantity contains the string value “3”.
  • The variable price has the value 56.73.
  • The unary plus operator (+) is used to convert a quantity’s string value to a number value. The outcome is saved in the variable quantity.
  • Total is calculated by multiplying quantity and price.
  • The total value is returned to the console via console.log ().
  • The number 170.19 will be output to the console, which is the product of 3 and 56.73.

Conclusion

In conclusion, we looked at various methods for how to change string to number in javascript, such as using the parseInt() function, parseFloat() function, Number() function and the Unary Plus operator. However, after weighing the benefits and drawbacks of each method, we recommend using the Number() function.

Because it can handle integers, floating-point numbers, and scientific notation. The Number( ) function is more versatile than any of  the parseInt( ) and parseFloat( ) functions. Furthermore, it is simpler and more concise than the Unary Plus operator, which can be difficult to read and understand.

Anyone can make their code more readable, maintainable, and error-free by using the Number( ) function. Overall, the Number() function is a versatile and powerful tool that can assist JavaScript developers in writing more efficient and effective code.