Serialize a Double to 2 decimal places using Jackson

Viewed 55466

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

In the JSON output, I'd like to restrict the amount to 2 decimal places. Currently it is shown as:

"amount":459.99999999999994

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.

Also, I tried using the @JsonSerialize annotation, with a custom serializer.
In the model:

@JsonSerialize(using = CustomDoubleSerializer.class)
public Double getAmount()

And serializer implementation:

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

The CustomDoubleSerializer "appears" to work. However, can anyone suggest any other simpler (or more standard) way of doing this.

5 Answers

I know that Double should not be used as a monetary amount. However, this is not my code.

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

That will serialize as 111.22. No custom serializers needed.

Regarding what was stated above, I just wanted to fix a little something, so that people won't waste time on it as I did. One should actually use

BigDecimal.valueOf(amount).xxx

instead of

new BigDecimal(amount).xxx

and this is actually somehow critical. Because if you don't, your decimal amount will be messed up. This is a limitation of floating point representation, as stated here.

Best way I have seen till now is to create a customized serializer and @JsonSerializer(using=NewClass.class). Wanted to try with @JsonFormat(pattern=".##") or so, but it may not work according one comment of OP(I think the formatter does not honor that)

See here: https://github.com/FasterXML/jackson-databind/issues/632

public class MoneyDeserializer extends JsonDeserializer<BigDecimal> {

    private NumberDeserializers.BigDecimalDeserializer delegate = NumberDeserializers.BigDecimalDeserializer.instance;

    @Override
    public BigDecimal deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        BigDecimal bd = delegate.deserialize(jp, ctxt);
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        return bd;
    }    
}

BUT, although more convenient and less code is written, usually, deciding the scale of a field is concern of business logic, not part of (de)serialization. Be clear about that. Jackson should be able to just pass the data as-is.

Related