How can I configure Jackson to use BigDecimal when parsing numbers?

80 Views Asked by At

When using Java and jackson-databind.jar file (com.fasterxml.jackson.core:jackson-databind:jar:2.14.2) I'm finding the last fractional digit of a 17 fractional digit number is lost, so I'm only getting 16 fractional digits after parsing the JSON string.

For example:

{
   "myval" : 0.09345678901234567
}

is stored as 0.0934567890123456646023214489105157554149627685546875 (based on debugger). To test this I wrote some simple Java code:

        String string17Digits = "0.09345678901234567";
        double double17Digits =  0.09345678901234567;
        BigDecimal test17Digits1 = new BigDecimal(string17Digits);
        BigDecimal test17Digits2 = new BigDecimal(double17Digits);
        BigDecimal test17Digits3 = new BigDecimal(0.09345678901234567);

When I examine these values inside the debugger, I see the problem. Debugger showing values

So my belief (not yet proven) is that somewhere in Jackson-Databind when the JSON is being converted from a string to a number value a double datatype is being used to store the number.

I'm searching for a way to configure Jackson to use BigDecimal as the underlying datatype when converting strings to numbers.

Searching for solution

  1. What is the precision for a Java double?
    See theserverside.com article, JavaSE article and Java datatypes - These articles while helpful didn't answer my basic question. How many fractional digits of precision can I get in a number less than 1?

  2. A google search for the answer says this here:

Precision: 15 to 17 significant digits, depending on usage. The number of significant digits does not depend on the position of the decimal point. Representation: The values are stored in 8 bytes, using IEEE 754 Double Precision Binary Floating Point format.

  1. Searching for a way to configure Jackson to use BigDecimal to store numbers that have been read when creating the internal NodeTree representation. I found Jackson reading all numbers as BigDecimal

I'm thinking this last one is the answer to my question so I'll check it out.

0

There are 0 best solutions below