Search code examples
javajsongsonbigdecimal

Serializing BigDecimal value using GSON


here is my code:

System.out.println(GSON.toJson(new BigDecimal(10.12)));

and the output is:

10.1199999999999992184029906638897955417633056640625

Is it possible to limit the precision of BigDecimal value that GSON serialize? i.e. my expected output of serialized value is:

10.11

Solution

  • This is not a GSON issue. new BigDecimal() try to represent double accurately and ends up taking lot more digits.

    You can use BigDecimal.valueOf(10.12) or new BigDecimal("10.12") instead of new BigDecimal().

    System.out.println(GSON.toJson(BigDecimal.valueOf(10.12)));