javagson

lost decimals when json deserialization use Gson


public class GsonTest {
    class A {
        Float v;
    }

    public static void main(String[] args) {
        Gson gson = new Gson();
        String aStr = "{ v:2752293.58 }";

        A a = gson.fromJson(aStr, A.class);
        System.out.println(a.v);

    }
}

the result will be: 2752293.5

not the expected value: 2752293.58

anyone have the same problem?


Solution

  • The fundamental problem is not anything to do with JSON or Gson. Rather it is your use of Float (or float).

    The Float and float types simply cannot represent 2752293.58 with full precision. For example,

    public class FloatTest {
        public static void main(String[] args) {
            Float v = 2752293.58F;
            System.out.println(v);
        }
    }
    

    This outputs

    2752293.5
    

    In this case, you could use either Double (or double) or BigDecimal. But note that all of these types have limits on the precision of the numbers that they can represent.

    This Q&A explains the difference between the two most commonly used floating point types ... which correspond to Java's float and double types.