gpt4 book ai didi

java - 使用 GSON 序列化 BigDecimal 值

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:21:35 51 4
gpt4 key购买 nike

这是我的代码:

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

输出为:

10.1199999999999992184029906638897955417633056640625

是否可以限制 GSON 序列化的 BigDecimal 值的精度?即我的序列化值的预期输出是:

10.11

最佳答案

这里的问题不在于 GSON,而是在于您的 BigDecimal 值。

如果您使用 new BigDecimal(double value) 构造函数,您可能会得到不可预知的结果。

如果你看一下BigDecima(double value) constructor documentation它清楚地说:

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.

所以最好使用 BigDecimal String constructor 这里:

new BigDecimal("10.12")

关于java - 使用 GSON 序列化 BigDecimal 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45076637/

51 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com