title: Serialize a Double to 2 decimal places using Jackson
body: <p>I'm using <code>Jackson</code>, with <code>Spring MVC</code>, to write out some simple objects as <code>JSON</code>. One of the objects, has an <code>amount</code> property, of type <code>Double</code>. (I know that <code>Double</code> should not be used as a monetary amount. However, this is not my code.) </p>
  
  <p>In the <code>JSON</code> output, I'd like to restrict the amount to 2 decimal places. Currently it is shown as:
      </p>
  
  <pre><code>"amount":459.99999999999994
  </code></pre>
  
  <p>I've tried using Spring 3's <code>@NumberFormat</code> annotation, but haven't had success in that direction. Looks like others had issues too: <a href="https://jira.springsource.org/browse/SPR-6731">MappingJacksonHttpMessageConverter's ObjectMapper does not use ConversionService when binding JSON to JavaBean propertiesenter link description here</a>.</p>
  
  <p>Also, I tried using the <code>@JsonSerialize</code> annotation, with a custom serializer.<br>
  In the model:
      </p>
  
  <pre><code>@JsonSerialize(using = CustomDoubleSerializer.class)
  public Double getAmount()
  </code></pre>
  
  <p>And serializer implementation:
      </p>
  
  <pre><code>public class CustomDoubleSerializer extends JsonSerializer&lt;Double&gt; {
      @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);
          }
      }
  }
  </code></pre>
  
  <p>The <code>CustomDoubleSerializer</code> "appears" to work. However, can anyone suggest any other simpler (or more standard) way of doing this.</p>