- Разобрать строку в число с плавающей запятой или int в Java
- 1. Использование Double.parseDouble() метод
- 2. Использование Float.parseFloat() метод
- 3. Использование Integer.parseInt() метод
- 4. Использование Number class
- Java Convert String to double
- Java Convert String to Double
- Double.parseDouble()
- Double.valueOf()
- new Double(String s)
- DecimalFormat parse()
- Converting Between Numbers and Strings
- Converting Numbers to Strings
- Java Convert String to Double examples
- 1. Java Convert String to Double using Double.parseDouble(String)
- Example 1: Java Program to convert String to double using parseDouble(String)
- 2. Java Convert String to Double using Double.valueOf(String)
- Example 2: Java Program to convert String to double using valueOf(String)
- 3. Java Convert String to double using the constructor of Double class
- Example 3: Java Program to convert String to double using the constructor of Double class
- References:
- How to convert String to Double in Java
- Conversion Modes
- parseDouble(String) method
- What if String is not convertible to double
- Using valueOf(String) method
Разобрать строку в число с плавающей запятой или 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
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
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.
Converting Between Numbers and Strings
Frequently, a program ends up with numeric data in a string objecta value entered by the user, for example.
The Number subclasses that wrap primitive numeric types ( Byte , Integer , Double , Float , Long , and Short ) each provide a class method named valueOf that converts a string to an object of that type. Here is an example, ValueOfDemo , that gets two strings from the command line, converts them to numbers, and performs arithmetic operations on the values:
public class ValueOfDemo < public static void main(String[] args) < // this program requires two // arguments on the command line if (args.length == 2) < // convert strings to numbers float a = (Float.valueOf(args[0])).floatValue(); float b = (Float.valueOf(args[1])).floatValue(); // do some arithmetic System.out.println("a + b = " + (a + b)); System.out.println("a - b = " + (a - b)); System.out.println("a * b = " + (a * b)); System.out.println("a / b = " + (a / b)); System.out.println("a % b = " + (a % b)); >else < System.out.println("This program " + "requires two command-line arguments."); >> >
The following is the output from the program when you use 4.5 and 87.2 for the command-line arguments:
a + b = 91.7 a - b = -82.7 a * b = 392.4 a / b = 0.0516055 a % b = 4.5
Note: Each of the Number subclasses that wrap primitive numeric types also provides a parseXXXX() method (for example, parseFloat() ) that can be used to convert strings to primitive numbers. Since a primitive type is returned instead of an object, the parseFloat() method is more direct than the valueOf() method. For example, in the ValueOfDemo program, we could use:
float a = Float.parseFloat(args[0]); float b = Float.parseFloat(args[1]);
Converting Numbers to Strings
Sometimes you need to convert a number to a string because you need to operate on the value in its string form. There are several easy ways to convert a number to a string:
int i; // Concatenate "i" with an empty string; conversion is handled for you. String s1 = "" + i;
// The valueOf class method. String s2 = String.valueOf(i);
Each of the Number subclasses includes a class method, toString() , that will convert its primitive type to a string. For example:
int i; double d; String s3 = Integer.toString(i); String s4 = Double.toString(d);
The ToStringDemo example uses the toString method to convert a number to a string. The program then uses some string methods to compute the number of digits before and after the decimal point:
public class ToStringDemo < public static void main(String[] args) < double d = 858.48; String s = Double.toString(d); int dot = s.indexOf('.'); System.out.println(dot + " digits " + "before decimal point."); System.out.println( (s.length() - dot - 1) + " digits after decimal point."); >>
The output of this program is:
3 digits before decimal point. 2 digits after decimal point.
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)
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)
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:
How to convert String to Double in Java
With the introduction of different data types, the need for conversion of one data type to another has come into being. In this article, we are going to see how we can convert from a String data type into Double data type.
Conversion Modes
There are two ways in which String data can be converted into double. They are:
- Using the static method parseDouble(String) of the java.lang.Double wrapper class
- Using the static method valueOf(String) of the java.lang.Double wrapper class
- Using the constructor of Double wrapper class that takes String as its parameter
Let us see both the modes and how to do them.
parseDouble(String) method
The class java.lang.Double has a static method called parseDouble(String) that allows the programmer to easily convert a String containing decimal data into the corresponding Double value. The function returns a Double value.
Let us see a code snippet to illustrate the same:
The above code on execution provides the following output:
What if String is not convertible to double
If String is not convertible to double, you will get below exception.
Exception in thread “main” java.lang.NumberFormatException: For input string: “35.126df”
at java.base/jdk.internal.math.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:2054)
at java.base/jdk.internal.math.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
at java.base/java.lang.Double.parseDouble(Double.java:543)
at org.arpit.java2blog.java8.ConvertStringToDouble.main(ConvertStringToDouble.java:8)
Using valueOf(String) method
You can also use valueOf(String) method to convert String to double in java. You can call Double’s doubleValue() to convert it to primitive type.