Precision Problem Between Java and Sql Server when Data Size is big

a11xaf1n  于 2023-05-16  发布在  Java
关注(0)|答案(2)|浏览(101)

I have a Java application that calculates the sum of Data using the type Double , and an Sql query that Calculates the sum using Float type.

To verify the data we do a sum check between another app using Java and our Sql Database. And we have a tolerance of 2 numbers difference.

This solution always worked for me and was able to get the same sum in both sides.

Lately it stopped working and started returning differences of thousands.Specificly when it's tested on a volumenous chunk of data ( Talking about sum result of 100billions).

Not sure if the volumetry has any impact on the precisions problem, but I would like a hand of help to understand the problem behind this precision problem, and if there is anyway I can make it work in all cases no matter how small or big the data is.

The choise of the Java Type and Sql Type was taken based on the mapping between these two langages : Link Here . ( Also It was Tested and gave the expected results).

My Java Code is smthg similar to this :

sumPrice += Double.valueOf(price);

My Sql Sum Query :

select sum(CONVERT(float, price)) ) from table where 'filter only Numeric values'

The price column is a varchar type for some specifications reasons.

Many Thanks

I tried using Decimal(38,4) but had the precision problem still.

For example with the last chunky data , in java we have a total : 5 555 555 555 555.55 but in sql we get 5 555 555 522 222.22 .

Before this problem, it will normally return in java 5 555 555 555 555.55 and in sql 5 555 555 555 522.22 ( 2 digit difference).

rta7y2nd

rta7y2nd1#

The solution is to use BigDecimal type in Java. It is equivalent to database DECIMAL and/or NUMBER and should be mapped correctly by JDBC driver. You can specify precision and scale for BigDecimal . Similar to the database types. And specify how to round the results. BigDecimal is the datatype for financial applications like banking where any loss of accuracy in calculations is unacceptable.

vyswwuz2

vyswwuz22#

Java Float and Double are not exact types. BigInteger or BigDecimal can perform arithmetic computations with arbitrary precision and can be a great solution.

Now, if your apps need to add and subtract values with two decimal places, sometimes it's easy to get them multiplied by 100 as a long . Then it's easy to add and subtract longs -- without losing any precision. When saving back to the database, just divide by 100.

相关问题