Parse string to double in java

Java — Convert String to double

static double parseDouble(String s): Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.

double d1 = Double.parseDouble("99.90"); System.out.println(d1); // 99.9 double d2 = Double.parseDouble("99.901"); System.out.println(d2); // 99.901 double d3 = Double.parseDouble("99.9010D"); System.out.println(d3); // 99.901 double d4 = Double.parseDouble("-99.909d"); System.out.println(d4); // -99.909 

Double.valueOf()

static Double valueOf(double d)​: Returns a Double instance representing the specified double value.

double d1 = Double.valueOf("88.80"); System.out.println(d1); // 88.9 double d2 = Double.valueOf("88.801"); System.out.println(d2); // 88.801 double d3 = Double.valueOf("88.8010d"); System.out.println(d3); // 88.801 double d4 = Double.valueOf("-88.808D"); System.out.println(d4); // -88.808 

Implicit casting automatically unbox Double into double.

Читайте также:  Java imageicon from file

Deprecated: Double‘s Constructor

It is rarely appropriate to use this constructor. Use parseDouble(String) to convert a string to a double primitive, or use valueOf(String) to convert a string to a Double object.

double d1 = new Double("123"); System.out.println(d1); // 123 double d2 = new Double("-88.808D"); System.out.println(d2); // -88.808D double d3 = new Double("FF00"); // NumberFormatException System.out.println(d3); 

DecimalFormat.parse()

parse​(String source) throws ParseException: Parses text from the beginning of the given string to produce a number. The method may not use the entire text of the given string.

import java.text.DecimalFormat; import java.text.ParseException;
DecimalFormat decimalFormat = new DecimalFormat(); try < double l = decimalFormat.parse("456.0990D").doubleValue(); System.out.println(l); // 456.99 >catch (ParseException e)

We also can use external libraries like Apache Commons NumberUtils, Spring’s NumberUtils, and Google’s Guava primitive Doubles.

Apache Commons NumberUtils

  • static double toDouble(String str): Convert a String to a double, returning 0.0d if the conversion fails.
  • static double toDouble(String str, double defaultValue): Convert a String to a double, returning a default value if the conversion fails.
  • static Double createDouble(String str): Convert a String to a Double.
import org.springframework.util.NumberUtils;
double d1 = NumberUtils.toDouble("365.536"); System.out.println(d1); // 365.536 double d2 = NumberUtils.toDouble(""); System.out.println(d2); // 0.0 double d3 = NumberUtils.toDouble("365.5360D", 0); System.out.println(d3); // 365.536 double d4 = NumberUtils.toDouble("xyz", -1); System.out.println(d4); // -1.0 double d5 = NumberUtils.toDouble("", -1); System.out.println(d5); // -1.0 double d6 = NumberUtils.createDouble("365.5360d"); System.out.println(d6); // 365.536 double d7 = NumberUtils.createDouble("-#88FF"); // NumberFormatException System.out.println(d7); 

Spring NumberUtils

Similar like in Converting String to int and Converting String to long, we can use Spring’s NumberUtils to parse String to number (in this case double).

import org.springframework.util.NumberUtils;
double d1 = NumberUtils.parseNumber("95.085", Double.class); System.out.println(d1); // 95.085 double d2 = NumberUtils.parseNumber("-31.490", Double.class); System.out.println(d2); // -31.49 

Google Guava Doubles.tryParse()

static Double tryParse(String string): Parses the specified string as a double-precision floating point value.

import com.google.common.primitives.Longs;
double d1 = Doubles.tryParse("512.345"); System.out.println(d1); // 512.345 double d2 = Doubles.tryParse("-512.3450D"); System.out.println(d2); // -512.345 

Liked this Tutorial? Share it on Social media!

Источник

Разобрать строку в число с плавающей запятой или 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() метод, который анализирует строку как десятичное целое число со знаком.

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

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

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

Источник

Java Convert String to double

Java Convert String to double

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Java String to double conversion can be done by many ways. Today we will look into some common ways to convert java string to double primitive data type or Double object. Note that since java supports autoboxing, double primitive type and Double object can be used interchangeably without any issues.

Double d1 = 10.25d; //autoboxing from double to Double double d = Double.valueOf(10.25); //unboxing from Double to double 

Java Convert String to Double

java convert string to double, java string to double

Let’s look at all the different ways to convert string to double in java.

Double.parseDouble()

We can parse String to double using parseDouble() method. String can start with “-” to denote negative number or “+” to denote positive number. Also any trailing 0s are removed from the double value. We can also have “d” as identifier that string is a double value. This method returns double primitive type. Below code snippet shows how to convert string to double using Double.parseDouble() method.

String str = "+123.4500d"; double d = Double.parseDouble(str); // returns double primitive System.out.println(d); //-123.45, trailing 0s are removed System.out.println(Double.parseDouble("123.45001")); //123.45001 System.out.println(Double.parseDouble("123.45001d")); //123.45001 System.out.println(Double.parseDouble("123.45000")); //123.45 System.out.println(Double.parseDouble("123.45001D")); //123.45001 

Double.valueOf()

This method works almost similar as parseDouble() method, except that it returns Double object. Let’s see how to use this method to convert String to Double object.

String str = "123.45"; Double d = Double.valueOf(str); // returns Double object System.out.println(d); //123.45 System.out.println(Double.valueOf("123.45d")); //123.45 System.out.println(Double.valueOf("123.4500d")); //123.45 System.out.println(Double.valueOf("123.45D")); //123.45 

new Double(String s)

We can convert String to Double object through it’s constructor too. Also if we want double primitive type, then we can use doubleValue() method on it. Note that this constructor has been deprecated in Java 9, preferred approach is to use parseDouble() or valueOf() methods.

String str = "98.7"; double d = new Double(str).doubleValue(); //constructor deprecated in java 9 System.out.println(d); //98.7 

DecimalFormat parse()

This is useful to parse formatted string to double. For example, if String is “1,11,111.23d” then we can use DecimalFormat to parse this string to double as:

String str = "1,11,111.23d"; try < double l = DecimalFormat.getNumberInstance().parse(str).doubleValue(); System.out.println(l); //111111.23 >catch (ParseException e)

That’s all for converting string to double in java program. Reference: Double API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

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:

Источник

Разобрать строку в число с плавающей запятой или 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() метод, который анализирует строку как десятичное целое число со знаком.

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

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

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

Источник

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