Java parsing string to double

How can I parse the string to Double

developer.android.com/reference/java/lang/Double.html a lot of problems like these can be solved by using the Reference available.

6 Answers 6

Well what you passed was an integer and not a string.

@Mohit. well on SO you should post your complete code or else you will get answers like this (or somewhat complete)

Probably the string is ending up containing something other than the two digits for whatever reason? The code would probably help, yes.

I have a suspicion that there is a leading or trailing space. It could be something more exotic, but its usually the simple things.

It shouldn’t be Double.parseDouble(78) but Double.parseDouble(«78») instead.

In that case it shouldn’t give you any exception.

You need to put quotes around your parameter.

Well, I strongly suspect that the value of the string variable you’re passing in actually isn’t a valid number. I suggest you log the Unicode value of each character, so you can see exactly what’s in there.

The code you’ve given (passing the string «78») should be absolutely fine. but you may have some extra, invisible characters in your real string. Logging the exact values should make that clear.

before you parse your string variable , use the method trim() in order to be sure that your string contain only numbers , , try this :

myStringToParse = myStringToParse.trim(); Double.parseDouble(myStringToParse); 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Parsing String to Double [duplicate]

I’m trying to parse String into Double, and I’m not sure if it is the correct way to do it. If anyone can help me check on it, and give feedback I’d really appreciate it. Here’s the code:

 String amount = enterAmount.getText().toString(); double subtotal = Double.valueOf(amount).doubleValue(); 

Welcome to StackOverflow. When an answer helped you out of your problem, you should accept it by clicking the tick next to the answer.

Читайте также:  Фоновое изображение с помощью HTML

you can use 2 methods to parse double. 1. double subtotal = Double.valueOf(amount); 2. double subtotal = Double.parseDouble(amount);

7 Answers 7

double subtotal = Double.parseDouble(amount); 
String amount = enterAmount.getText(); double subtotal = Double.parseDouble(amount); 

You should wrap this call around a try-catch block and handle NumberFormatException which will be thrown if the string cannot be parsed as Double .

double subtotal = Double.parseDouble(amount); 

What I do, is (when using a JFormattedTextField or a JTextField ) replacing all the comma’s by points and removing the spaces:

String amount = enterAmount.getText(); amount = amount.replace(",",".").replace(" ", ""); double subtotal = Double.parseDouble(amount); 

This means following input will work:

12 1,2 1.2 200 000 200 000,01 

The commas are used in a lot of European countries: Wikipedia

You should use some logic to determine if it is a valid number. Here is a function for testing integers:

public static int validateInteger(String number) < int i = -1; try < i = Integer.parseInt(number); >catch (NumberFormatException nfe) <> catch (NullPointerException npe) <> return i; >

In your case, you have to change the Integer.parseInt() function into whatever type you want.

The function is not static in the sense that you can’t change it. If you want to allow the number -1 then that is of course perfectly fine. Choose another return value, any number, with a very low probability of being a correctly entered number. I used this function to test if a port number was valid and since negative numbers can’t be used as port numbers, the number -1 was a good indication of this.

you are right that any invalid value could be used. You could return a long, or you could just throw the NumberFormatException an have the caller catch it rather than check the value.

Источник

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.

Читайте также:  Магические методы python ооп

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.

Источник

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

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

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

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

Читайте также:  Append columns in python

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: Parsing a string to a double

I’m reading a file into an array and trying to take out the numbers and put them as a double in an array of their own. And apparently my middle name must be «Error». From what I can tell the code is ok. at least theres nothing jumping out at me. Here it is in all it’s glory.

import java.io.BufferedInputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.*; import java.lang.Object.*; public class ReadFromFile < public static void main (String[] args)< File file = new File("vector10.txt"); FileInputStream fis = null; BufferedInputStream bis = null; DataInputStream dis = null; StringBuffer sb = new StringBuffer(); String string = new String(); try< fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInputStream(bis); while((string=dis.readLine()) != null)< sb.append(string+"\n"); >fis.close(); bis.close(); dis.close(); System.out.println(sb); String newString = sb.toString(); System.out.println(newString); String[] doubles = newString.split(","); for (int i=0; i Double arrDouble[] = new Double[doubles.length]; int idx = 0; for(String s : doubles) < arrDouble[idx++] = Double.parseDouble(s); >> catch (FileNotFoundException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> > 
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48) at java.lang.Long.parseLong(Long.java:412) at java.lang.Long.parseLong(Long.java:461) at ReadFromFile.main(ReadFromFile.java:51) 

Programming is not necessarily my strong point and my eyes are starting to bleed looking at the screen. Any thoughts or tips are gratefully appreciated. Cheers

Источник

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