Reputation: 1583
Is there anyway to prevent Java from turning my double into exponential value? I am having problem with saving that into my database. It keep telling me that it can not convert my VarChar into numeric.
I do;
amt = oldAmt - amt;
amt = Math.abs(amt);
And put the value in amt like so using setter;
jvd.setDr_amt(amt);
Then generate a query string using a function and it give me;
INSERT INTO jv ( id, dr_amt) VALUES (1, 1.595545786E7);
The datatype in the database for dr_amt is numeric(15, 2)
Anyone?
Upvotes: 1
Views: 1733
Reputation: 339836
You should be using JDBC prepared statements, with bound parameters, e.g.
PreparedStatement s = c.prepareStatement(
"INSERT INTO mytable (myfield) VALUES (?)");
s.setDouble(1, n);
s.executeUpdate();
[exception handling code omitted]
The JDBC layer will ensure that your double variable is correctly sent to the database server without getting mangled.
Upvotes: 4
Reputation: 220952
I'm very much guessing that you do something like this:
connection.createStatement().executeUpdate(
"INSERT INTO my_table VALUES('" + myDouble + "')");
Don't do that for the following reasons:
Write your statement in a way to let JDBC handle data types:
PreparedStatement stmt = connection.prepareStatement(
"INSERT INTO my_table VALUES(?)");
stmt.setDouble(1, myDouble);
stmt.executeUpdate();
If you absolutely must inline your double value in your SQL string instead of using bind values, try using BigDecimal
to serialise your double, instead:
new BigDecimal(myDouble).toString();
Since you seem to be operating on monetary values, you should change all your doubles to BigDecimal
anyway, as BigDecimal
is Java's best match for SQL's DECIMAL
data type
Upvotes: 7