简体   繁体   中英

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? ie my expected output of serialized value is:

10.11

The problem here isn't with GSON but with your BigDecimal value instead.

If you use the new BigDecimal(double value) constructor you can have unpredictable results.

If you take a look at BigDecima(double value) constructor documentation it clearly says :

Notes:

  • The results of this constructor can be somewhat unpredictable. One might assume that writing new BigDecimal(0.1) in Java creates a BigDecimal which is exactly equal to 0.1 (an unscaled value of 1, with a scale of 1), but it is actually equal to 0.1000000000000000055511151231257827021181583404541015625. This is because 0.1 cannot be represented exactly as a double (or, for that matter, as a binary fraction of any finite length). Thus, the value that is being passed in to the constructor is not exactly equal to 0.1, appearances notwithstanding.

  • The String constructor, on the other hand, is perfectly predictable: writing new BigDecimal("0.1") creates a BigDecimal which is exactly equal to 0.1, as one would expect. Therefore, it is generally recommended that the String constructor be used in preference to this one.

So it's better to use the BigDecimal String constructor here:

new BigDecimal("10.12")

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)));

Instead of relying on the constructor of BigDecimal the best practice is to format it to the desired precision before serializing it with GSON.

BigDecimal provides a method to convert it to float ( floatValue ) and you can use the String.format(expr, float) function to format it as you wish.

    BigDecimal value = new BigDecimal(10.12);

    String strValue = String.format("%.2f", value.floatValue());
    System.out.println(GSON.toJson(strValue));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM