Java input string to double

How to convert String to Double in Java and double to String with Example

There are three ways to convert a String to double value in Java, Double.parseDouble() method, Double.valueOf() method and by using new Double() constructor and then storing the resulting object into a primitive double field, autoboxing in Java will convert a Double object to the double primitive in no time. Out of all these methods, the core method is parseDouble() which is specially designed to parse a String containing floating-point value into the Double object. Rest of the methods like valueOf() and constructor uses parseDouble() internally. This method will throw NullPointerException if the string you are passing is null and NumberFormatException if String is not containing a valid double value e.g. containing alphabetic characters.

Some of you might be curious and thinking if one method can do the job then why we have three methods for String to Double or double conversion? Well, their purpose is a little bit different and they also provide some other service.

For example, you should be using Double.valueOf() method if you frequently need to convert String to Double because it will likely give better performance by caching frequently used values just like Integer.valueOf() method does. On the other hand, if you use a new Double(String value) constructor then you will always get a new Double object, creating memory pressure for your application.

BTW, in this article, we will not only learn how to convert String to double value but also how to convert Double to String, as it’s important to know both sides of a conversion. If you are not looking to convert String to double but to format double values to String, then please check my earlier post, formatting floating-point numbers in Java.

String to Double Conversion in Java

As I said, the following are three main ways to convert a String containing floating-point value into double primitive and Double object. You don’t need to worry about which method returns a double primitive value and which method returns Double object because autoboxing will take care of double to Double object conversion automatically.

  • String concatenation
  • Double.toString() method
  • String.valueOf() method
Читайте также:  Css переключатель on off

The second method is mainly for the Double objects, but don’t worry even if you have a double value you can leverage autoboxing to first convert it into a Double object and then just call the toString() method on it to get an equivalent String in Java.

The third method uses the valueOf() method of the String class to convert a double value to a String. Since String provides a set of overloaded methods to convert every single data type like boolean, short, char, int, long, float, and double it makes sense to leverage that. Just like other valueOf() methods this can also cache frequently used values along with leveraging String pool.

String to Double to String Conversion in Java

Double to String — Java Code Example

Enough of theory, now let’s see some code in working. In the following example, we will first learn how to convert a String to double and then opposite. We will use the knowledge we gain in the first two paragraphs.

import java.util.Arrays; import java.util.List; /** * Java Program to convert String to double in Java and vice-versa. * * @author WINDOWS 8 */ public class StringToDoubleDemo< public static void main(String args[])< // let's first start converting String to double // there are three ways to convert a String to double in Java // parseDouble(), valueOf() and Double() constructor // Using parseDouble() to parse String to double in Java String number = "6.24"; double d = Double.parseDouble(number); System.out.println("String " + number +" is parse to double value : " + d); // now let's use Double.valueOf() method to get double from String String str = "8.23"; double value = Double.valueOf(str); System.out.println("String to double conversion using valueOf : " + value); // another way is by using Double wrapper class constructor // though it will return Double value, autoboxing will convert // it to double primitive value String floating = "122.44"; double converted = new Double(floating); System.out.println("Double value " + converted + " created from String " + floating ); // Now let's do opposite by converting a double value to String in Java // again there are three way to get a String value from double // by String concatenation, valueOf() and toString() method // Simplest way to convert a double to String double pie = 3.14; String parsed = "" + pie; System.out.println("Double value : " + pie + " String value : " + parsed); // you can also use String.valueOf() to convert double to String double myValue = 88.22; String doubled = String.valueOf(myValue); System.out.println("Double value " + myValue + " converted to String : " + doubled); // another way to get String from double is by using Double.toString() // in Java Double code = new Double(5543.3); String decode = code.toString(); System.out.println("double : " + code + " String : " + decode); > >

That’s all about how to convert String to Double in Java and vice-versa. Now you know how you can convert these two frequently used data types into one other. For the sake of best practice, just remember to use Double.valueOf() if you frequently need to convert String to double because it can cache values, it will result in better performance.

Читайте также:  Php one file framework

Similarly, when you convert a double to String using String concatenation, make sure to use empty String literal and that too as the first argument otherwise + operator will not perform concatenation.

  • How to convert Map to List in Java (tutorial)
  • How to convert float to String in Java? (tutorial)
  • How to convert Byte array to String in Java? (tutorial)
  • How to convert Double to Long in Java? (tutorial)
  • How to convert String to Int in Java? (example)
  • How to convert Array to String in Java? (tutorial)
  • 5 Ways to convert Java 8 Stream to List? (solution)
  • Best way to Convert Numbers to String in Java? (guide)
  • How to convert binary numbers to decimals in Java? (tutorial)
  • How to convert java.util.Date to java.sql.Date in Java? (tutorial)
  • 5 examples to convert InputStream to String in Java? (tutorial)
  • How to convert Enum to String in Java? (guide)
  • How to convert Character to String in Java? (tutorial)
  • How to convert Array to Set and List in Java? (example)
  • 3 examples to convert Array to ArrayList in Java (tutorial)
  • How to convert SQL date to Util Date in Java? (example)
  • How to convert ArrayList to Set in Java? (tutorial)
  • How to convert Hexadecimal numbers to octal and binary in Java? (tutorial)
  • How to convert lowercase String to uppercase in Java? (example)
  • How to convert String to Enum in Java? (tutorial)
  • How to convert List to Set in Java? (example)

Источник

Разобрать строку в число с плавающей запятой или int в Java

В этом посте мы обсудим, как преобразовать строку в число double, float или int в Java.

1. Использование Double.parseDouble() метод

Стандартное решение для анализа строки для получения соответствующего двойного значения использует метод Double.parseDouble() метод.

The Double.parseDouble() броски метода NumberFormatException если строка не содержит анализируемого двойника. Чтобы избежать внезапного завершения программы, заключите свой код в блок try-catch.

Обратите внимание, вы не можете анализировать такие строки, как 1.1 с использованием Integer.parseInt() метод. Чтобы получить целочисленное значение, вы можете привести результирующее двойное значение.

2. Использование Float.parseFloat() метод

В качестве альтернативы вы можете использовать Float.parseFloat() метод для синтаксического анализа строки в число с плавающей запятой.

Чтобы получить целочисленное значение, приведите результирующее значение с плавающей запятой, как обсуждалось ранее.

3. Использование Integer.parseInt() метод

Чтобы получить целочисленное значение, представленное строкой в десятичном виде, вы можете использовать Integer.parseInt() метод, который анализирует строку как десятичное целое число со знаком.

Читайте также:  Html button title font

4. Использование Number class

Чтобы проанализировать текст с начала заданной строки для получения числа, вы можете использовать метод parse() метод NumberFormat учебный класс. Этот метод может не использовать всю строку и выдает ParseException если строка начинается с любого неразборчивого нечислового символа.

The NumberFormat.parse() метод возвращает Number экземпляр класса, который предлагает intValue() , longValue() , floatValue() , doubleValue() , byteValue() , а также shortValue() методы для получения значения указанного числа в качестве соответствующего типа метода.

Источник

Java Convert String to Double examples

In this guide we will see how to convert String to Double in Java. There are three ways to convert String to double.

1. Java – Convert String to Double using Double.parseDouble(String) method
2. Convert String to Double in Java using Double.valueOf(String)
3. Java Convert String to double using the constructor of Double class – The constructor Double(String) is deprecated since Java version 9

1. Java Convert String to Double using Double.parseDouble(String)

public static double parseDouble(String str) throws NumberFormatException

This method returns the double representation of the passed String argument. This method throws NullPointerException , if the specified String str is null and NumberFormatException – if the string format is not valid. For example, if the string is “122.20ab” this method would throw NumberFormatException.

String str="122.202"; double dnum = Double.parseDouble(str);

The value of variable dnum of double type would be 122.202 after conversion.

Lets see the complete example of the conversion using parseDouble(String) method.

Example 1: Java Program to convert String to double using parseDouble(String)

Java Convert String to double using parseDouble()

Output:

2. Java Convert String to Double using Double.valueOf(String)

The valueOf() method of Double wrapper class in Java, works similar to the parseDouble() method that we have seen in the above java example.

String str = "122.111"; double dnum = Double.valueOf(str);

The value of dnum would be 122.111 after conversion

Lets see the complete example of conversion using Double.valueOf(String) method.

Example 2: Java Program to convert String to double using valueOf(String)

Convert String to double in Java using valueOf()

Output:

3. Java Convert String to double using the constructor of Double class

Note: The constructor Double(String) is deprecated since Java version 9

String str3 = "999.333"; double var3 = new Double(str3);

Double class has a constructor which parses the String argument that we pass in the constructor, and returns an equivalent double value.

public Double(String s) throws NumberFormatException

Using this constructor we can create a new object of the Double class by passing the String that we want to convert.

Example 3: Java Program to convert String to double using the constructor of Double class

In this example we are creating an object of Double class to convert the String value to double value.

References:

Источник

Оцените статью