I’ve been reading up on the net about the issues with handling float and double types in java. Unfortunately, the image is still not clear. Hence, i’m asking here direct. 🙁
My MySQL table has various DECIMAL(m,d) columns. The m may range from 5 to 30. d stays a constant at 2.
Question 1.
What equivalent data-type should i be using in Java to work (i.e store, retrieve, and process) with the size of the values in my table? (I’ve settled with double – hence this post).
Question 2.
While trying to parse a double from a string, i’m getting errors
Double dpu = new Double(dpuField.getText());
for example –
"1" -> java.lang.NumberFormatException: empty String
"10" -> 1.0
"101" -> 10.0
"101." -> 101.0
"101.1" -> 101.0
"101.19" -> 101.1
What am i doing wrong? What is the correct way to convert a string to a double value?
And what measures should i take to perform operations on such values?
EDIT
This is the code –
System.out.println(dpuField.getText());
Double dpu = new Double(dpuField.getText());
System.out.println(dpu);
Yes, the problem lies with getText() reporting the wrong value of the dpuField.
This method is called on the JTextField keyTyped event. So what’s going wrong here?
EDIT 2
Looking at :
http://journals.ecs.soton.ac.uk/java/tutorial/post1.0/ui/keylistener.html
Apparently, keyTyped() does not give me the keycode. I’ll have to switch to keyRealeased()
Since it’s a
DECIMALfield, you should preferjava.math.BigDecimal. You can store it in DB usingPreparedStatement#setBigDecimal()and you can retrieve it from DB usingResultSet#getBigDecimal().This can’t be true. The problem lies somewhere else. Maybe it is just not returning the data you expect to be returned or you are not using/debugging the values you expect them to be.