使用 Jackson 将 Double 序列化为 2 个小数位 [英] Serialize a Double to 2 decimal places using Jackson
问题描述
我使用 Jackson
和 Spring MVC
,将一些简单的对象写成 JSON
.其中一个对象具有 amount
属性,类型为 Double
.(我知道 Double
不应该用作货币金额.但是,这不是我的代码.)
I'm using Jackson
, with Spring MVC
, to write out some simple objects as JSON
. One of the objects, has an amount
property, of type Double
. (I know that Double
should not be used as a monetary amount. However, this is not my code.)
在 JSON
输出中,我想将数量限制为 2 位小数.目前显示为:
In the JSON
output, I'd like to restrict the amount to 2 decimal places. Currently it is shown as:
"amount":459.99999999999994
我尝试过使用 Spring 3 的 @NumberFormat
注释,但在这方面没有成功.看起来其他人也有问题:MappingJacksonHttpMessageConverter 的 ObjectMapper 在将 JSON 绑定到 JavaBean 属性时不使用 ConversionService 在此处输入链接描述.
I've tried using Spring 3's @NumberFormat
annotation, but haven't had success in that direction. Looks like others had issues too: MappingJacksonHttpMessageConverter's ObjectMapper does not use ConversionService when binding JSON to JavaBean propertiesenter link description here.
此外,我尝试使用带有自定义序列化程序的 @JsonSerialize
注释.
在模型中:
Also, I tried using the @JsonSerialize
annotation, with a custom serializer.
In the model:
@JsonSerialize(using = CustomDoubleSerializer.class)
public Double getAmount()
和序列化器实现:
public class CustomDoubleSerializer extends JsonSerializer<Double> {
@Override
public void serialize(Double value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonGenerationException {
if (null == value) {
//write the word 'null' if there's no value available
jgen.writeNull();
} else {
final String pattern = ".##";
//final String pattern = "###,###,##0.00";
final DecimalFormat myFormatter = new DecimalFormat(pattern);
final String output = myFormatter.format(value);
jgen.writeNumber(output);
}
}
}
CustomDoubleSerializer
似乎"起作用了.但是,任何人都可以提出任何其他更简单(或更标准)的方法来做到这一点.
The CustomDoubleSerializer
"appears" to work. However, can anyone suggest any other simpler (or more standard) way of doing this.
推荐答案
我知道
Double
不应用作货币金额.然而,这不是我的代码.
I know that
Double
should not be used as a monetary amount. However, this is not my code.
确实不应该.BigDecimal
是存储货币金额的更好选择,因为它无损 并且可以更好地控制小数位.
Indeed, it should not. BigDecimal
is a much better choice for storing monetary amounts because it is lossless and provides more control of the decimal places.
所以对于确实可以控制代码的人来说,它可以这样使用:
So for people who do have control over the code, it can be used like this:
double amount = 111.222;
setAmount(new BigDecimal(amount).setScale(2, BigDecimal.ROUND_HALF_UP));
这将序列化为 111.22
.无需自定义序列化程序.
That will serialize as 111.22
. No custom serializers needed.
这篇关于使用 Jackson 将 Double 序列化为 2 个小数位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!