How to convert string to double - java

double d=0.0;
for (String k : word.keySet()) {
System.out.println(k + "\t" + word.get(k));
d+=Double.valueOf(word.get(k));
d+=word.get(k);
word.get(k);
}
System.out.println("Value\t"+d);
The values are in hashmap. Incompatible type error occurs in 5th line.how to correct it?

The line d+=Double.valueOf(word.get(k)); will correctly add the Double value of word.get(k) to your double d, provided the String is parsable as Double.
The line after it, however, adds a String to a double, which will not compile.
The last line in your loop doesn't make any sense, you are invoking get without actually using the value.

You can use Double.parseDouble()
Eg:
String str="2.25";
double d=Double.parseDouble(str);
System.out.println(d);

You can convert String value to Double like this--
double latitu=Double.parseDouble("21.2186653");

If the error is in 5th line that's because you are trying to add whatever you have in the set word with double d. Java do not know what you have in the set word so you can type cast it if the word is a set of double. Otherwise you have to parse the double from what "word.get(k)" returns.
try d+=(double) word.get(k), if word is a set of double
or d+=double.valueOf(word.get(k)). if you have string in the set word.

In your 5th line of sample code, you are trying to add a string value with a double. that's why you are getting error
use
d += Double.parseDouble(word.get(k));
rather than
d+=word.get(k)

Related

NumberFormatingExcepton if App is launched First Time

I have 4 TextViews. 3 of them display results of EditText input value in another activity, and it's saved with shared preferences.
The fourth TextView needs to display sum of that previous 3 TextViews.
I get the error: NumberFormatingException invalid double ""
This is my code:
// GETTING VALUES FOR FIRST 3 TEXTVIEWS
textViewRezultat1RMPotisakSKlupe.setText(settings.getString("benchSave", null));
textViewRezultat1RMCucanj.setText(settings.getString("squatSave", null));
textViewRezultat1RMMrtvoDizanje.setText(settings.getString("deadSave", null));
//LITTLE BIT OF MATH TO GET VALUE OF FOURTH
double prvo = Double.parseDouble(textViewRezultat1RMPotisakSKlupe.getText().toString());
double drugo = Double.parseDouble(textViewRezultat1RMCucanj.getText().toString());
double trece = Double.parseDouble(textViewRezultat1RMMrtvoDizanje.getText().toString());
double rezultat = 0;
rezultat = (prvo + drugo + trece);
textViewRezultat1RMUkupno.setText(Double.toString(rezultat));
That works like a charm.
The problem is, I get the error I mentioned above if the app is launched for the first time (with no stored data).
Can anyone help me solve it?
Actually the problem occurs when trying to parse a double from a string that is not representing a number or just simply null.
parseDouble
public static double parseDouble(String s)
throws NumberFormatException
Returns a new double initialized to the value represented by the specified String, as performed by the valueOf method of class Double.
Parameters:
s - the string to be parsed.
Returns: the double value represented by the
string argument.
Throws:
NullPointerException - if the string is null
NumberFormatException - if the string does not contain a parsable
double.
So you need to test both scenarios to be sure you are not in either of the faulty cases.
String prvoString = textViewRezultat1RMPotisakSKlupe.getText().toString();
Double prvo;
if(prvoString != null) { //shouldn't occur
try {
prvo = Double.parseDouble(prvoString);
} catch (NumberFormatException ex) { //inputs like "" or "banana"
//Tell the user he is entering invalid input
}
}
So why is this occuring when your app is running for the first time? The code that is parseDouble is executed when your view is loaded and trying to parse empty ("") strings.
Before doing double prvo = Double.parseDouble() always check whether your Strings are valid or not because if your String is empty, that is like "", you can't convert this to Double as its not a number.
So before every Double.parseDouble check like this -
if (!TextUtils.isEmpty(yourString))
Double.parseDouble(yourString);

Parsing string to double/float throwing errors

I am extracting couple of values like 1234, 2456.00 etc from UI as string. When I try to parse this string to float, 1234 is becoming 1234.0 and when I tried to parse as double its throwing error. How can I solve this?
I am using selenium web driver and java. Below are few things I tried.
double Val=Double.parseDouble("SOQ");
double Val=(long)Double.parseDouble("SOQ");``
I think you mixed it up a bit when trying to figure out how to parse the numbers. So here is an overview:
// lets say you have two Strings, one with a simple int number and one floating point number
String anIntegerString = "1234";
String aDoubleString = "1234.123";
// you can parse the String with the integer value as double
double integerStringAsDoubleValue = Double.parseDouble(anIntegerString);
System.out.println("integer String as double value = " + integerStringAsDoubleValue);
// or you can parse the integer String as an int (of course)
int integerStringAsIntValue = Integer.parseInt(anIntegerString);
System.out.println("integer String as int value = " + integerStringAsIntValue);
// if you have a String with some sort of floating point number, you can parse it as double
double doubleStringAsDoubleValue = Double.parseDouble(aDoubleString);
System.out.println("double String as double value = " + doubleStringAsDoubleValue);
// but you will not be able to parse an int as double
int doubleStringAsIntegerValue = Integer.parseInt(aDoubleString); // this throws a NumberFormatException because you are trying to force a double into an int - and java won't assume how to handle the digits after the .
System.out.println("double String as int value = " + doubleStringAsIntegerValue);
This code would print out:
integer String as double value = 1234.0
integer String as int value = 1234
double String as double value = 1234.123
Exception in thread "main" java.lang.NumberFormatException: For input string: "1234.123"
Java will stop "parsing" the number right when it hits the . because an integer can never have a . and the same goes for any other non-numeric vales like "ABC", "123$", "one" ... A human may be able to read "123$" as a number, but Java won't make any assumptions on how to interpret the "$".
Furthermore: for float or double you can either provide a normal integer number or anything with a . somewhere, but no other character besides . is allowed (not even , or ; and not even a WHITESPACE)
EDIT:
If you have a number with "zeros" at the end, it may look nice and understandable for a human, but a computer doesn't need them, since the number is still mathematically correct when omitting the zeros.
e.g. "123.00" is the same as 123 or 123.000000
It is only a question of formatting the output when printing or displaying the number again (in which case the number will be casted back into a string). You can do it like this:
String numericString = "2456.00 "; // your double as a string
double doubleValue = Double.parseDouble(numericString); // parse the number as a real double
// Do stuff with the double value
String printDouble = new DecimalFormat("#.00").format(doubleValue); // force the double to have at least 2 digits after the .
System.out.println(printDouble); // will print "2456.00"
You can find an overview on DecimalFormat here.
For example the # means "this is a digit, but leading zeros are omitted" and 0 means "this is a digit and will not be omitted, even if zero"
hope this helps
Your first problem is that "SOQ" is not a number.
Second, if you want create a number using a String, you can use parseDouble and give in a value that does not have a decimal point. Like so:
Double.parseDouble("1");
If you have a value saved as a long you do not have to do any conversions to save it as a double. This will compile and print 10.0:
long l = 10l;
double d = l;
System.out.println(d);
Finally, please read this Asking a good question
The problem is you cannot parse non-numeric input as a Double.
For example:
Double.parseDouble("my text");
Double.parseDouble("alphanumeric1234");
Double.parseDouble("SOQ");
will cause errors.
but the following is valid:
Double.parseDouble("34");
Double.parseDouble("1234.00");
The number you want to parse into Double contains "," and space so you need first to get rid of them before you do the parsing
String str = "1234, 2456.00".replace(",", "").replace(" ", "");
double Val=Double.parseDouble(str);

Parse double from JFormattedTextField

I've got a bug or something. I have a method that saves an article, like this:
class SaveArticleListener implements ActionListener {
//....
String s = textArticlePrice.getText().replace(',','.').replaceAll("\\s","");
double price = Double.parseDouble(s);
//....
}
Where textArticlePrice is a JFormattedTextField which configured like:
NumberFormat priceFormat = NumberFormat.getNumberInstance();
priceFormat.setMaximumFractionDigits(2);
priceFormat.setMinimumFractionDigits(2);
textArticlePrice = new JFormattedTextField(priceFormat);
textArticlePrice.setColumns(10);
And in the parseDouble method I'm getting every time:
java.lang.NumberFormatException: For input string: "123 456 789.00"
So replace works with a dot, but not with whitespace... Why?
You'd be better off using your NumberFormat to parse the String. Keep a reference to priceFormat, and then use
double price = priceFormat.parse(textArticlePrice.getText()).doubleValue();
The formatter that's being used to display the number is the same one then used to turn it back into a double so you know it's going to be parsing it in a compatible way.
Best of all is
double price = ((Number) textArticlePrice.getValue()).doubleValue();
which should work without any need for conversion if you've set your JFormattedTextField up properly. (The getValue() call returns an Object, so you need to cast it. It might return a Double or a Long, depending on what's in the text field, so the safe way to get a double out of it is to treat it as a Number, which is the supertype of both, and invoke its .doubleValue() method.)
Writing something that converts it into something that can be parsed by Double.parseDouble() is really not the right way to go because it's too fragile if the formatting of your text field changes later on.
Regarding your question" why doesn't it work with white spaces". White spaces are chars just like a,l,#,?,¡, but it only recognises ,12345, numbers together as a number, you cant make an int variable 'int number = 1 234; Its the same with parsing. Rather try,
s = s.replace(',','.');
s = s.replace(" ","");
Price = Double.parseDouble(s);
Assuming that '123 456 789.00' is one number.
please comment if this helped.
I did this now, it worked fine
String strNumber = "1 2 3 4 5 6.789";
double DblNumber = Double.parseDouble(strNumber);
System.out.Println(DblNumber);// this displays the number if your IDE has an output window

Format double value?

I have following line of code:
DecimalFormat df = new DecimalFormat("#.##");
System.out.println(df.format(23.00));
System.out.println(Double.parseDouble(df.format(23.00d)));
System.out.println(df.parse("23.00").doubleValue());
First line print 23 but in 2nd and 3rd line when i convert it to double it prints 23.0 . showing 23.0 doesnt makes any sense.
How can i get a double value 23.
I checked these best-way-to-format-a-double-value-to-2-decimal-places how-to-nicely-format-floating-numbers-to-string-without-unnecessary-decimal-0
In the second and third output lines, you're just using Double.toString effectively. A double value doesn't remember whatever format it happens to have been parsed in to start with - it's just a numeric value.
If you want to format a value in a particular way, use df.format as you have in your first output line. For example:
String text = ...; // Wherever you get the text from
double value = Double.parseDouble(text);
String formatted = df.format(value); // Using the df you set up before
A double value, when converted to a String, will NEVER be an integer. It will always contains decimals.
If you want to print to the console a double as 23, you can cast it to an Int:
System.out.println((int) yourDouble);
When you say double if your number is 23, it shown 23.0 because it is double.
If your meaning is to print an int value with 2-digits, you can use System.out.printf("%.2d", number);
I don't have any Java compiler on my system this time for test that, but I think it is true.

explain " double value = Double.valueOf(fstNmElmntLst.item(k).getTextContent()); "

What does this statement do?
double value = Double.valueOf(fstNmElmntLst.item(k).getTextContent());
Quite a lot going on there...
Gets the text content from some list as a string
converts the string to a Double (object wrapper for primitive double)
unboxes the Double to a primitive double
We could break it down
String tmp = fstNmElmntLst.item(k).getTextContent(); // fetch some string
Double wrapper = Double.valueOf(tmp); // convert (parse string to a number)
double value = wrapper; // unbox
A more efficient way to do this would be to use the parseDouble utility function. This avoids an unnecessary intermediate object being created:
double value = Double.parseDouble(fstNmElmntLst.item(k).getTextContent());
If you're new to java, have a look at some starter tutorials on the oracle.com site, for example Number Classes tutorial. If you're ever unsure of a behaviour of particular function just look at the javadocs. Just google something like "Double.valueOf javadoc 6" or setup your IDE properly.
Here's the javadoc for Double.valueOf(String). It will give you the full info on expected inputs, outputs, and other useful info like exceptions, in this case the NumberFormatException, which is thrown if your text can't be interrupted as a number.
It takes a text content of an item with index k from some kind of list fstNmElmntLst and parses that text as a double value.
This is casting from string to double because of array element, but there should be array value numeric else exception will raise.
Apparently getTextContent returns String. The typical way to convert String to double is to use the valueOf method in the class Double. As one can convert from Double to the primitive type double, the way to convert a String to double is to pass the string to valueOf in Double.

Categories