使用GSON序列化BigDecimal值 [英] Serializing BigDecimal value using GSON

查看:476
本文介绍了使用GSON序列化BigDecimal值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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

,输出为:

10.1199999999999992184029906638897955417633056640625

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

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

10.11

推荐答案

这不是 GSON 问题. new BigDecimal()尝试准确地表示双精度数,并最终占用更多的数字.

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

您可以使用 BigDecimal.valueOf(10.12) new BigDecimal("10.12")代替 new BigDecimal().

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

这篇关于使用GSON序列化BigDecimal值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆