Search code examples
javafloating-pointjacksonnumber-formatting

Format a float as fixed point with Jackson


I've searched the Jackson docs, but can't find any good documentation for the pattern of @JsonFormat for floating point numbers.

Given a field

@JsonProperty("Cost")
private Double cost;

How can I get Jackson to format it as fixed point number with four digits precision in decimal format with @JsonFormat?

PS: I know one should not use floats for money. Spare us the discussion, please.


Solution

  • Building on @Veselin's answers I'm using

    public class DoubleDecimalSerializerWithSixDigitPrecisionAndDotSeparator
        extends JsonSerializer<Double> {
    
      @Override
      public void serialize(Double value, JsonGenerator generator, SerializerProvider serializers)
          throws IOException {
        generator.writeNumber(String.format(Locale.US, "%.6f", value));
      }
    }
    

    The use case is the generation of CSVs in Germany, so I don't care for JSON formatting and want a "." as a decimal separator.