Consider SQL statement INSERT INTO table (field) VALUES (-0.11111111)
with field
Oracle type NUMBER.
When the value to be inserted is of type float or double, you get the exact value in field
, i.e. -0.11111111.
But when the value to be inserted is of type BigDecimal
, you get the value padded with random numbers, i.e. 0.1111111099999999990428634077943570446223.
Why?
Java states that "BigDecimal
is an immutable, arbitrary-precision signed decimal numbers."
The code is:
String sql = "INSERT INTO pat_statistics (file_key,test_number,rqw)"
+ " VALUES (3778, 100, " + new BigDecimal(-0.11111111) + ")";
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, pwd);
Statement st = conn.createStatement();
int n = st.executeUpdate(sql);
The DB is Oracle.
For a literal value you should always use the BigDecimal constructor taking a string argument. See the documentation of the BigDecimal(double) constructor for details.
You are creating the BigDecimal from a float so it will reflect exactly the value of the float, and as you probably know the trailing digits of a float are more ore less random.
I assume you see this int he database because the jdbc driver thinks: Hey I am getting a BigDecimal. I can use all the digits I can master.
When you use float or double the jdbc driver knows I cann't rely on all the digits and ignores what comes after that threshhold.
If you need the additional precision of Big Decimal, create it from a String or calculate it from Integegers.
=== another correction ====
The handling is not done by the jdbc driver, but by the various toString conversions, since you are assembling your SQL String.
BTW: you really should use bind variables for this.