Open In App

How to Convert a String to an Numeric in Java?

Last Updated : 12 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In Java programming, there are situations in which we must convert a string of numeric characters into one of the following data types: double, float, long, or int. To execute arithmetic operations and other numerical calculations, this conversion is necessary. We will look at how to convert a string to numeric types in Java in this tutorial.

String to Numeric Conversion in Java

In Java, we may utilize the wrapper classes and their corresponding parse methods to transform a string to a numeric type. For instance, Long.parseLong() for long, Float.parseFloat() for float, Double.parseDouble() for double, and Integer.parseInt() for converting to an int. Managing exceptions is essential because, if the string does not represent a valid numeric value, the conversion can generate a NumberFormatException.

Syntax:

Long varLong=Long.parseLong(str);
int varInt = Integer.parseInt(intString);
float varFloat = Float.parseFloat(floatString);
double varDouble = Double.parseDouble(doubleString);

Convert a String to an Numeric in Java

Let’s look at several instances of how to convert various numeric types from a string:

Java




public class StringToNumericExample {
    public static void main(String[] args) {
        // Example 1: Convert String to int
        String intString = "123";
        int convertedInt = Integer.parseInt(intString);
        System.out.println("Converted int: " + convertedInt);
  
        // Example 2: Convert String to long
        String longString = "9876543210";
        long convertedLong = Long.parseLong(longString);
        System.out.println("Converted long: " + convertedLong);
  
        // Example 3: Convert String to float
        String floatString = "45.67";
        float convertedFloat = Float.parseFloat(floatString);
        System.out.println("Converted float: " + convertedFloat);
  
        // Example 4: Convert String to double
        String doubleString = "123.456";
        double convertedDouble = Double.parseDouble(doubleString);
        System.out.println("Converted double: " + convertedDouble);
    }
}


Output

Converted int: 123
Converted long: 9876543210
Converted float: 45.67
Converted double: 123.456



Explanation of the above Program:

  • The examples show how to convert strings that represent numerical values to double, float, long, and int.
  • For conversion, the parse methods of the corresponding wrapper classes—Integer, Long, Float, and Double—are used.
  • After that, the converted numbers are shown on the console.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads