java

How To Convert String To Double In Java

When converting from string to double, it is important that the string contains a valid double value. However, to convert from string to int there are several things to consider.
 

How to Convert String To A Simple Double

The class Double contains a static method, which can be used to achieve exactly that:

Double.parseDouble(String s)

This method takes a string that must be formatted correctly. This means that it consists exclusively of digits, separated by a maximum of one dot. Only one plus or minus character is allowed at the beginning.

Double.parseDouble("");       // Error - no numbers
Double.parseDouble("1");      // correct
Double.parseDouble("1.1");    // correct
Double.parseDouble(".1");     // correct
Double.parseDouble(".");      // Error - no numbers
Double.parseDouble("-1");     // correct
Double.parseDouble("+1");     // correct
Double.parseDouble("1.1");    // correct
Double.parseDouble(" 1");     // correct - Whitespaces at start and end are ignored
Double.parseDouble("1,1");    // Error - Comma not allowed
Double.parseDouble("1_000");  // Error - Separator not allowed

A string containing illegal characters causes a java.lang.NumberFormatException.
 
[st_adsense]  

How to Convert String To Double Object

To convert a string into Double class object, there is the static method Double.valueOf(String s):

Double i = Double.valueOf("1");

Of course you can also assign the result of Double.parseDouble() to a double object by autoboxing:

Double i = Double.parseDouble("1");
java-mcq-multiple-choice-questions-and-answersJava MCQ – Multiple Choice Questions and Answers – OOPsThis collection of Java Multiple Choice Questions and Answers (MCQs): Quizzes & Practice Tests with Answer focuses on “Java OOPs”.   1. Which of the…Read More mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More [st_adsense]

Leave a Reply

Your email address will not be published. Required fields are marked *