BigDecimal variable padded with random numbers in JDBC Insert

泪湿孤枕 提交于 2019-12-11 07:06:24

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/5074735/bigdecimal-variable-padded-with-random-numbers-in-jdbc-insert

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!