How To Convert String To Number In Java

In java string is a sequence of characters where a number is a numeric value,

Conversion of a string to a number means that we need to take a string that represents a numeric value and convert it to its relative or corresponding numeric type in Java.

For example,” suppose we have the string “123”, which represents the integer value 123. To convert the given  string to an integer, we can use the Integer.parseInt() as a specific method in Java, which takes a string as input and returns the corresponding integer values.

Note that whenever we are converting any string value to number in Java, the string must represent a valid numeric value for the corresponding numeric type. String containing characters which cannot be parsed as a number, a NumberFormatException will be thrown.

Additionally, it is very important to find that any string being converted does not contain any leading or trailing whitespace characters in between as they will cause the conversion to fail. It is also important to ensure that the converted value is within the valid range for the target numeric type.

It’s important to validate the string before attempting to convert it to avoid the NumberFormatException.

Why to convert string to number in java

A string to a number conversion in Java is useful for a variety of reasons.

The following are few typical circumstances where it might be required to convert :

  1. User input: A string is frequently used to represent user input that you get. The user may input the numbers as strings if you are creating a calculator application, for instance. In order to execute mathematical operations on the strings, you must transform the strings to integers.
  2. File management: Data is often in the form of a string when reading or writing to a file. To do any mathematical operations, you must convert the strings to integers if the data in the file comprises numerical values.
  3. Data manipulation: To execute operations like sorting or filtering based on numerical values, you may need to transform texts to numbers while working with data.
  4. Database operations: Data in a database is frequently in the form of a string while it is being retrieved or stored. To execute any mathematical operations, you must transform the strings to integers if the data contains numerical values.

In conclusion, while working with numerical data in Java especially, when the data is represented as strings, it would be important to convert a string to a number.

Methods For Converting string to number in java :

Depending on the type of number we want to convert a string to in Java, there are a variety of approaches. Following are the some basic methods which can be used for conversion of string to number in java:

  1. Integer.parseInt(String str) – to convert a string to an integer
  2. Double.parseDouble(String str) – to convert a string to a double
  3. Long.parseLong(String str) – to convert a string to a long
  4. Float.parseFloat(String str) – to convert a string to a float
  5. BigDecimal(String str) – to convert a string to a BigDecimal

It’s important to handle the NumberFormatException that may occur if the string does not represent a valid number.

Approach1: How to convert string to number in java Using Integer.parseInt(String str)

This method returns the string as a primitive type int. If the string does not contain any valid integer then it will throw a NumberFormat Exception.

So, every time when we convert a string to an int we need to take care of these exceptions by placing the code inside the try-catch block.

We can convert a string to an integer in Java using the Integer.parseInt(String str) method. Here is an example:

public class StringToIntegerExample {
   public static void main(String[] args) {
       // Declare a string variable
       String str = "123";

       try {
           // Convert the string to an integer using the parseInt() method
           int num = Integer.parseInt(str);

           // Print the converted integer
           System.out.println("Converted string to integer: " + num);
       } catch (NumberFormatException e) {
           // If the string cannot be converted to an integer, catch the NumberFormatException
           System.out.println("Error: " + e.getMessage());
       }
   }
}

Output:

Converted string to integer: 123

Explanation:

  1. Declare a String variable str and initialize it with the value “123”.
  2. Use the parseInt() method of the Integer class to convert the string to an integer and store the result in the int variable num.
  3. Surround the conversion code with a try-catch block to handle the NumberFormatException that may be thrown if the string cannot be parsed as an integer.
  4. After conversion of a given string we can print the integer value which is converted using the System.out.println() method.
  5. In case of any unwanted exception print an error message to the console using the getMessage() method of the caught exception.

Approach 2: How to convert string to number in java Using Double.parseDouble(String str)

To convert a string to a double in Java using Double.parseDouble(String str), We simply need to pass the string representation of the number to the method. The method that returns a double value representing the converted string.

If the string cannot be parsed to a double, the method will throw a NumberFormatException. You should handle this exception or validate the input string before attempting to convert it to avoid runtime errors.

Code:

public class StringToDoubleExample {
   public static void main(String[] args) {
       // The string we want to convert to a double
       String str = "3.14";
      
       try {
           // Convert the string to a double using Double.parseDouble()
           double num = Double.parseDouble(str);
          
           // Print the converted double to the console
           System.out.println("Converted string to double: " + num);
       } catch (NumberFormatException e) {
           // Handle the exception if the string cannot be parsed to a double
           System.out.println("Error: " + e.getMessage());
       }
   }
}

Output:

Converted string to double: 3.14

Explanation: 

  1. Declare a String variable str and initialize it with the value “3.14”.
  2. Use the parseDouble() method of the Double class to convert the string to a double and store the result in the double variable num.
  3. Surround the conversion code with a try-catch block to handle the NumberFormatException that may be thrown if the string cannot be parsed as a double.
  4. If the conversion is successful, print the converted double to the console using the System.out.println() method.
  5. If any exception is thrown, print an error message as output of code using the getMessage() method of the caught exception.

Approach 3: How to convert string to number in java Using Long.parseLong(String str)

To convert a string to a long integer in Java using Long.parseLong(String str), you simply need to pass the string representation of the number to the method. The method returns a long integer value representing the converted string.

Here’s an example of how to use Long.parseLong(String str) to convert a string to a long integer in Java, including comments explaining each step of the code:

Code:

public class StringToLongExample {
   public static void main(String[] args) {
       // The string we want to convert to a long integer
       String str = "123456789";
      
       try {
           // Convert the string to a long integer using Long.parseLong()
           long num = Long.parseLong(str);
          
           // Print the converted long integer to the console
           System.out.println("Converted string to long integer: " + num);
       } catch (NumberFormatException e) {
           // Handle the exception if the string cannot be parsed to a long integer
           System.out.println("Error: " + e.getMessage());
       }
   }
}

Output:

Converted string to long integer: 123456789

Explanation:

  1. Declare a String variable str and initialize it with the value “123456789”.
  2. Use the parseLong() method of the Long class to convert the string to a long integer and store the result in the long variable num.
  3. Surround the conversion code with a try-catch block to handle the NumberFormatException that may be thrown if the string cannot be parsed as a long integer.
  4. After performing the above tasks, we need to print the converted long integer to the console using the System.out.println() method.
  5. In case an exception is thrown, catch it and print an error message as output using the getMessage() method of the caught exception.

Approach 4:How to convert string to number in java Using Float.parseFloat(String str)

To convert a string to a float in Java using Float.parseFloat(String str), you just need to pass the string representation of the float to the method. The method returns a floating-point value representing the converted string.

If the string cannot be parsed to a float, the method will throw a NumberFormatException. You should handle this exception or validate the input string before attempting to convert it to avoid runtime errors.

Code:

public class StringToFloatExample {
   public static void main(String[] args) {
       // The string we want to convert to a float
       String str = "3.14";
      
       try {
           // Convert the string to a float using Float.parseFloat()
           float num = Float.parseFloat(str);
           // Print the converted float to the console
           System.out.println("Converted string to float: " + num);
       } catch (NumberFormatException e) {
           // Handle the exception if the string cannot be parsed to a float
           System.out.println("Error: " + e.getMessage());
       }
   }
}

Output:

Converted string to float: 3.14

Explanation:

  1. We define a class called StringToFloatExample.
  2. Inside the class, we define a main method which is the entry point of the program.
  3. We declare a string variable str and assign it the value “3.14”. This is the string we want to convert to a float.
  4. We are using try-catch block to catch any exceptions which may be thrown during the conversion process.
  5. Inside the try block, we use the Float.parseFloat() method to convert the string to a float and assign the result to a float variable num.
  6. We print the converted float to the console using System.out.println().
  7. Inside the catch block, we handle the exception if the string cannot be parsed to a float by printing the error message using e.getMessage().

Approach 5: How to convert string to number in java Using BigDecimal(String str)

With Java’s function Object() { [native code] } BigDecimal, you can turn a string into a BigDecimal (String str). When working with big or exact values that can’t be precisely represented by simple data types like int, long, float, or double, this is helpful.

import java.math.BigDecimal;

public class StringToBigDecimalExample {
   public static void main(String[] args) {
       // The string we want to convert to a BigDecimal
       String str = "123456789.123456789";
      
       // Create a new BigDecimal object using the input string
       BigDecimal bigDecimal = new BigDecimal(str);
      
       // Print the converted BigDecimal to the console
       System.out.println("Converted string to BigDecimal: " + bigDecimal);
   }
}

Output:

Converted string to BigDecimal: 123456789.123456789

Explanation:

  1. The code imports the BigDecimal class from the java.math package.
  2. A string value is assigned to the str variable, which represents the value we want to convert to a BigDecimal object.
  3. A new BigDecimal object is created using the input string. The constructor BigDecimal(String str) takes a string representation of a decimal value and returns a BigDecimal object that represents the same value.
  4. The converted BigDecimal object is printed to the console using System.out.println().

A BigDecimal created from a string cannot have its value changed directly because BigDecimal objects are immutable. Instead, we must use one of the BigDecimal arithmetic methods to construct a brand-new BigDecimal object with the desired value.

Best Approach to Convert string to number in java:

If we need to make quick and basic converts, the Integer.parseInt(String str) method is really the ideal choice for converting a string to an integer. The following justifies why this is a wise course of action:

  1. Simplicity: The Integer.parseInt(String str) method is very easy to use. The string we wish to convert is simply sent in as an argument, and the function returns the integer value of that text.
  1. Speed: The Integer.parseInt(String str) method is much faster and efficient. It is optimized for converting strings to integers, and is faster than many other conversion methods.
  1. Widely supported: A wide range of Java systems and versions support the Integer.parseInt(String str) function. It is a fundamental component of the Java language and is accessible in all Java releases.
  1. Built-in error handling: A NumberFormatException will only be thrown by the Integer.parseInt(String str) function if the input string is not a valid integer.. It is simple to handle erroneous input gracefully and prevent runtime issues thanks to the built-in error handling.

Due to this level of ease of use, speed, wide support, and built-in error handling, Integer.parseInt(String str) is said to be the best method for converting a string to an integer.

Sample Problem For Converting string to number in java :

Here are some examples of using Integer.parseInt(String str) to convert a string to an integer in real-world scenarios:

Sample Problem 1:

You are building a program that calculates the total cost of a shopping cart, based on the prices of the items in the cart. However, the prices are stored as strings, so you need to convert them to integers before adding them up.

Code:

import java.util.Scanner;

public class ShoppingCart {
  
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
      
       // initialize total cost to 0
       int totalCost = 0;
      
       // loop through the items in the shopping cart
       while (true) {
           // prompt the user to enter the price of the next item
           System.out.print("Enter the price of the next item (or 'done' to finish): ");
           String priceString = scanner.nextLine();
          
           // exit the loop if the user is done
           if (priceString.equals("done")) {
               break;
           }
          
           // convert the price string to an integer
           int price = Integer.parseInt(priceString);
          
           // add the price to the total cost
           totalCost += price;
       }
      
       // output the total cost
       System.out.println("The total cost is: " + totalCost);
      
       scanner.close();
   }

}

Output

Enter the price of the next item (or 'done' to finish): done
The total cost is: 0

Explanation:

This Java program is used for implementing a simple shopping cart that takes input from the user and calculates total cost of the items stored in the cart. Here’s a breakdown of how the program works:

  1. Import the Scanner class from the java.util package.
  2. Create a class called ShoppingCart that contains a main method.
  3. Create a new Scanner object to read user input.
  4. Initialize the total cost to 0.
  5. Use a while loop to repeatedly prompt the user to enter the price of the next item, and add it to the total cost. The loop will exit when the user enters “done”.
  6. Output the total cost to the console.
  7. Close the Scanner object to free up system resources.

Sample Problem 2:

You are building a program that prompts the user to enter their age and then calculates the number of days they have been alive.

Code:

import java.util.Scanner;

public class Main {

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
      
       // prompt the user for their age
       System.out.print("Enter your age: ");
       String ageString = scanner.nextLine();
       int age = Integer.parseInt(ageString);
      
       // calculate the number of days the user has been alive
       int daysAlive = age * 365;
      
       // output the result
       System.out.println("You have been alive for " + daysAlive + " days.");
      
       scanner.close();
   }

}

Output:

Enter your age: 35 
You have been alive for 12775 days.

Explanation:

  1. The program prompts the user to enter their age using the print statement and the Scanner class.
  2. The input is received as a string and stored in the variable ageString.
  3. The program converts the ageString to an integer using the Integer.parseInt method and stores the result in the variable age.
  4. The program calculates the number of days the user has been alive by multiplying their age by 365 and storing the result in the variable daysAlive.
  5. The program outputs the result using the print statement and the value of the daysAlive variable.

Sample Problem 3:

You are building a program that calculates the number of days between two dates entered by the user. The dates are stored as strings in the format “MM/DD/YYYY”, so you need to convert them to integers before calculating the difference.

The month, day, and year elements of the dates can be extracted and transformed into integers using the Integer.parseInt() method.

Code:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;

public class DateDifferenceCalculator {
  
   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
      
       // prompt the user to enter the first date
       System.out.print("Enter the first date in the format MM/DD/YYYY: ");
       String dateString1 = scanner.nextLine();
      
       // prompt the user to enter the second date
       System.out.print("Enter the second date in the format MM/DD/YYYY: ");
       String dateString2 = scanner.nextLine();
      
       // extract the month, day, and year components of the first date
       int month1 = Integer.parseInt(dateString1.substring(0, 2));
       int day1 = Integer.parseInt(dateString1.substring(3, 5));
       int year1 = Integer.parseInt(dateString1.substring(6));
      
       // extract the month, day, and year components of the second date
       int month2 = Integer.parseInt(dateString2.substring(0, 2));
       int day2 = Integer.parseInt(dateString2.substring(3, 5));
       int year2 = Integer.parseInt(dateString2.substring(6));
      
       // create LocalDate objects for the two dates
       LocalDate date1 = LocalDate.of(year1, month1, day1);
       LocalDate date2 = LocalDate.of(year2, month2, day2);
      
       // calculate the difference in days between the two dates
       long daysBetween = ChronoUnit.DAYS.between(date1, date2);
      
       // output the result
       System.out.println("The number of days between the two dates is: " + daysBetween);
      
       scanner.close();
   }

}

Output:

Enter the first date in the format MM/DD/YYYY: 03/08/2005
Enter the second date in the format MM/DD/YYYY: 12/22/2012
The number of days between the two dates is: 2846

Explanation:

  1. The program prompts the user to enter two dates in the format MM/DD/YYYY.
  2. The input is received as strings and stored in variables dateString1 and dateString2.
  3. The program extracts the month, day, and year components of the two dates by using the substring method to get the specific characters in the input string, and then converts them to integers using Integer.parseInt method.
  4. The program creates two LocalDate objects for the two dates by using the of method of the LocalDate class and passing the extracted year, month, and day components as arguments.
  5. The program calculates the difference in days between the two dates using the between method of the ChronoUnit class and passing the two LocalDate objects as arguments. The result is stored in the variable daysBetween.
  6. The program outputs the number of days between the two dates by printing a message that includes the value of the daysBetween variable.

Conclusion

In conclusion, the Java string to number conversion function transforms a number’s string representation into a numeric data type.

When we want to conduct arithmetic or comparison operations on a number that is represented as a string, we must make this conversion. To convert a string into number in java we have several methods to perform for the conversion such as Integer.parseInt(String str), Double.parseDouble(String str), Long.parseLong(String str), Float.parseFloat(String str), and BigDecimal (String str).

Java’s Integer method is the one that is most frequently used to translate strings into numbers parseInt(String str). After discussing the best approaches to convert strings to numbers using Java, we also solved some real-life scenario-based sample problems with proper code and explanations.