gpt4 book ai didi

java - Oracle ojdbc 驱动程序返回 NUMBER 类型列中整数值的浮点结果

转载 作者:行者123 更新时间:2023-11-30 08:02:52 26 4
gpt4 key购买 nike

我有Oracle 10g数据库和基于Spring 4.1.6框架的Java应用程序,它从Oracle中提取一些数据。我遇到一个问题,ojdbc 驱动程序返回 NUMBER 类型列中整数值的 float 结果。 ResultSet 元数据将对象类型标识为 BigDecimal。

列定义:MINUTES NUMBER 没有精度和小数位数实际值为“70”

我已经检查了 Oracle 10、11 和 12 ojdbc 驱动程序,每次相同的 Java 代码都会返回“70.0000000000000000000000000000000000002 作为该行中该列的值。我还检查了 Oracle SQL Developer 4.1 .1 并且它显示相同的不正确浮点值。

然而,Toad 显示正确的值“70”。

有什么想法吗?请再次注意:**此问题在 Oracle SQL Developer 4.1.1 中重现**

更新 - 下面的 Java 代码:

for (int j = 1; j <= count; j++) {
Object field = resultSet.getObject(j);
if (field != null) {
bufferedWriter.write(field.toString());
}
if (j < count) {
bufferedWriter.write(delimiter);
}
}

最佳答案

NUMBER 数据类型存储定点数和 float 。当您指定数字字段时,最好指定精度和小数位数。这提供了对输入的额外完整性检查。

NUMBER(精度、小数位数)

但是,如果未指定精度,则列将存储给定的值,即最大范围和最大精度(最多 38 位精度)。正如所给的,它在 java 中的行为就像Float。下面给出的示例输入示例:

Input              Stored As
7,456,123.89 7456123.89

更多信息请参见 Oracle Data Type

特别是这一部分:

Internal Numeric Format

Oracle Database stores numeric data in variable-length format. Each value is stored in scientific notation, with 1 byte used to store the exponent and up to 20 bytes to store the mantissa. The resulting value is limited to 38 digits of precision. Oracle Database does not store leading and trailing zeros. For example, the number 412 is stored in a format similar to 4.12 x 102, with 1 byte used to store the exponent(2) and 2 bytes used to store the three significant digits of the mantissa(4,1,2). Negative numbers include the sign in their length.

因此,如果您只想存储 Integer 值,请将列定义更改为 NUMBER(10,0),它尽可能接近 Integer java 。否则,从 BigDecimal

中去除尾随零

代码编辑:

for (int j = 1; j <= count; j++) {
BigDecimal field = (BigDecimal)resultSet.getObject(j);
if (field != null) {
bufferedWriter.write(field.stripTrailingZeros().toString());
}
if (j < count) {
bufferedWriter.write(delimiter);
}
}

或显式转换为整数(以丢失小数部分)

for (int j = 1; j <= count; j++) {
Integer field = (Integer)resultSet.getObject(j);
if (field != null) {
bufferedWriter.write(field.toString());
}
if (j < count) {
bufferedWriter.write(delimiter);
}
}

关于java - Oracle ojdbc 驱动程序返回 NUMBER 类型列中整数值的浮点结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31621901/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com