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.
Related
I am working on a pretty old Java application and I can not change Integer field to something else which can hold decimal values, so I need to convert some decimal string like "100.00", "3.33" "33.44" to Integer without loosing fractional values.
#Test
public void NumberFormatTest(){
String stringValue = "100.00";
int testTest = ? //what I can do here to get exact 100.00 in testTest variable ?
log.info("outPutValue {} ", testTest);
}
Currently its using Integer.parseInt(stringValue) and this is throwing
java.lang.NumberFormatException: For input string: "100.00"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
I am working on pretty old java code application and I can not change Integer field to something else which can hold decimal values
That is because int can only hold whole numbers. For decimal values you need to use float or double:
String s = "3.33";
double d = Double.parseDouble(s);
Alternatively, you might want to look into BigDecimal. Depending on your exact needs, this might be a better fit.
p.s. int, float and double are primitive types. Integer, Float and Double are class wrapper for those types. These are two different things. I recommend you read more about these differences to gain a better understanding.
Im adding three big decimals here, but it should give me accurate answer. I'm having two strings here and then converting to big decimal. Please dont ask why Im using strings. There is some business where I will get these values as string then I need to convert. Please find the code
BigDecimal a= new BigDecimal(100.05); --> This value I receive from web service. Its a decimal value from the service.
String b= "100.05";
String c= "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
Output it gives
400.1299999999999971578290569595992565155029296875
Where as it should be 400.13
The problem is your use of new BigDecimal(100.05). The value of a is then 100.0499999999999971578290569595992565155029296875.
If you had specified that value as a string instead, all would be well:
BigDecimal a = new BigDecimal("100.05");
String b = "100.05";
String c = "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
// Output: 400.13
If you only have the input as a double, you can use BigDecimal.valueOf(double) instead of calling the constructor:
BigDecimal a = BigDecimal.valueOf(100.05); // a is now exactly 100.05
Compare the BigDecimal(double) documentation:
Translates a double into a BigDecimal which is the exact decimal representation of the double's binary floating-point value. (...)
With that of BigDecimal.valueOf(Double):
Translates a double into a BigDecimal, using the double's canonical string representation provided by the Double.toString(double) method.
Note: This is generally the preferred way to convert a double (or float) into a BigDecimal, as the value returned is equal to that resulting from constructing a BigDecimal from the result of using Double.toString(double).
new BigDecimal(100.05)
This gives 100.0499999999999971578290569595992565155029296875, because 100.05 cannot be represented exactly as a double.
You have to use string here as well:
new BigDecimal("100.05")
As you get this value from a web-service, you probably convert it from a String to a float/double. If this is the case, just skip that conversion step.
If your web-service stub maps the return value to float/double, you can consider mapping it to a String directly and then feed it to BigDecimal constructor, like this:
double v = 100.05; // Value from web service
BigDecimal a= new BigDecimal(String.valueOf(v));
String b= "100.05";
String c= "200.03";
System.out.println(a.add(new BigDecimal(b).add(new BigDecimal(c))));
Live Example
That works because the string will only contain as many digits as are needed to differentiate the almost-100.05 value from the next value on either side that can be represented, and so we get the string "100.05", which then BigDecimal can process correctly.
You can format the answer to Decimal places using String.format and specifiying how many digits.
System.out.println(String.format("%.2f", a.add(new BigDecimal(b).add(new BigDecimal(c)))));
OK. I know that according to Java Docs:
parseFloat will return a NumberFormatException - if the string does not contain a parsable float.
I thought that the parseFloat method would see if the first character is a number and if it is then it will read until it finds a character and then return the value up until but not including the character as a Float.
So with that in mind I am attempting to do the following and getting a NumberFormatException.
float value;
value = Float.parseFloat("50C");
I was hoping that it would return with value = 50.
Can someone please explain why the above conversion would return a NumberFormatException? Did I misunderstand what the parseFloat would do?
According to the Java 7 docs on Float:
parseFloat(String s)
Returns a new float initialized to the value represented by the specified String, as performed by the valueOf method of class Float.
And for the valueOf method:
valueOf(String s)
Returns a Float object holding the float value represented by the argument string s.
So if the string passed to parseFloat method does not represent a float string, you will end up getting your NumberFormatException because it cannot convert it to a float.
Source: http://docs.oracle.com/javase/7/docs/api/java/lang/Float.html
The issue is that 50C cannot be parsed by the standard library as float number and hence the exception. To make it a float parseable you need to add character like F or f like 50f or 50F.
50C is not a parseable float only f, F,d,D are allowed.
Try:
value = Float.parseFloat("50f");
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]);
}
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+"";