Convert String to double - java

I am working on an assignment in which I have been given the task of creating an arraylist of books. In my utility, I have a 3 arg constructor (String title, String author, double price).
In my main, I am to read the contents of a comma seperated value file (which contains a list of book titles, authors, and price all on seperate lines). We are to tokenize the contents of the file (which I am able to do), and we are then to instantiate an ArrayList that holds book objects only. For each book in the text file, we are to read the record, tokenize the record, and create a new book object from the tokenized field, and then add the object to the beginning of the arrraylist.
So my question is:
When I tokenize the file (using the String method split, as the assignment dictates), I end up with a line by line break down of the file (as I should). I think I then want to feed these values into my constructor, but the constructor only accepts args String, String, double, and of course my tokenized file is String, String, String. Is there any way to 'convert' (for lack of a better term) the last string value into a double (I know that doubles are primitive and Strings are not), but I thought i would ask you guys before I go back to the drawing board and figure out the correct way of doing this.
Thanks for your time.

Call Double.parseDouble()
Here is the Javadoc

Double.parseDouble(d); will convert String "1.23" into double 1.23. There is also the related Integer.parseInteger(i) and Boolean.parseBoolean(b); functions.

What you want to do is parse a string into a double (giving you the words so that you know what it's called).
In Java, you use
Double.parseDouble(String)

You need to parse the string to a double, the code to do this would look like this:
Double num = Double.parseDouble(String);
Always make sure that the string is numberal before converting it else it will throw a error.

Webtest w= new Webtest();
ArrayList<String> dd= w.getarraylist();
Object []array1 = dd.toArray();
double value = Double.parseDouble(dd.get(8));
System.out.println(value);
double x[]=new double[dd.size()];
for (int i = 0; i <x.length; i++) {
x[i]=Double.parseDouble(dd.get(i));
System.out.println(x[i]);
}

Related

Multiplying ascii code and getting string back

I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others

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

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.

Using an input string in a textbox

I am trying to have the user input a number, and then that number is used to populate
a text field on a jform. However it keeps giving me errors. If I have the textfield call the str it gives me a numberformatexception, if I have it call the int variable it says it has to be a string...
public static String prePaidstr = "";
public static double prePaidint = 0;
prePaidstr =
JOptionPane.showInputDialog("Enter any amount prepaid:");
prePaidint = Double.parseDouble(prePaidstr);
jTextField13.setText(InvoiceSelectionUI.prePaidstr)
parseDouble converts a String into a Double, which is why it complains if you try to pass it a double.
A NumberFormatException is thrown when parseDouble is unable to successfully turn a String into a double; in this case it's because you're trying to parseDouble on an empty string. prePaidStr needs to contain something like "1.99" - e.g. something that, to a human, looks like a Double.
nm - I fixed it, just had one of the variables switched around

Java Double to String conversion without formatting

I have the number 654987. Its an ID in a database. I want to convert it to a string.
The regular Double.ToString(value) makes it into scientific form, 6.54987E5. Something I dont want.
Other formatting functions Ive found checks the current locale and adds appropriate thousand separators and such. Since its an ID, I cant accept any formatting at all.
How to do it?
[Edit] To clarify: Im working on a special database that treats all numeric columns as doubles. Double is the only (numeric) type I can retrieve from the database.
Use a fixed NumberFormat (specifically a DecimalFormat):
double value = getValue();
String str = new DecimalFormat("#").format(value);
alternatively simply cast to int (or long if the range of values it too big):
String str = String.valueOf((long) value);
But then again: why do you have an integer value (i.e. a "whole" number) in a double variable in the first place?
Use Long:
long id = 654987;
String str = Long.toString(id);
If it's an integer id in the database, use an Integer instead. Then it will format as an integer.
How about String.valueOf((long)value);
What about:
Long.toString(value)
or
new String(value)
Also you can use
double value = getValue();
NumberFormat f = NumberFormat.getInstance();
f.setGroupingUsed(false);
String strVal = f.format(value);
If what you are storing is an ID (i.e. something used only to identify another entity, whose actual numeric value has no significance) then you shouldn't be using Double to store it. Precision will almost certainly screw you.
If your database doesn't allow integer values then you should stored IDs as strings. If necessary make the string the string representation of the integer you want to use. With appropriate use of leading zeros you can make the alphabetic order of the string the same as the numeric order of the ints.
That should get you round the issue.
What about Long.toString((long)value) ?
double d = 56789;
String s = d+"";

Categories