
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert String to Double in Java
In this article, we will learn to convert string to double in Java. String to double is a very common need when dealing with user inputs, files, and APIs. There are several ways through which this process can be done in Java.
Problem Statement
Given a string representing a decimal number, convert it into a double in Java. The input string is guaranteed to be a valid numeric representation.
For example
Input
String str = "23.6";
Output
23.6
Different Approaches
The following are the two different approaches for converting string to double in Java ?
Using Double.parseDouble()
The Double.parseDouble() method is the most commonly used way to convert a string to a double. It belongs to the Double wrapper class and is efficient.
Converting the string to double using parseDouble() in Java ?
double res = Double.parseDouble("23.6");
Example
Below is an example of converting string to double using parseDouble() ?
public class Demo { public static void main(String args[]){ String str = "23.6"; double res = Double.parseDouble(str); System.out.println("Double (String to Double) = "+res); } }
Output
Double (String to Double) = 23.6
Time Complexity: O(1), as the conversion operation takes constant time.
Space Complexity: O(1), since no additional memory is allocated apart from storing the result.
Using Double.valueOf()
The Double.valueOf() method also converts a String to a double, but it returns an instance of double instead of a primitive double.
Converting the string to double using valueOf() in Java ?
Double numObj = Double.valueOf(numberStr);
Example
Below is an example of converting string to double using valueOf() ?
public class Main { public static void main(String[] args) { String numberStr = "99.99"; Double numObj = Double.valueOf(numberStr); double num = numObj; // Unboxing System.out.println("Converted double: " + num); } }
Output
Converted double: 99.99
Time Complexity: O(1), as the conversion operation takes constant time.
Space Complexity: O(1), since no additional memory is allocated apart from storing the result.
Conclusion
Converting a String to a double in Java is straightforward using Double.parseDouble() or Double.valueOf(). Both methods provide efficient ways to handle numerical string conversions. While parseDouble() returns a primitive double, valueOf() returns a Double object, making it useful when working with collections.