Aman Singh
Aman Singh

Reputation: 1104

Gson: Format double values to 4 decimal places

How can I go about making Gson format double values round (or truncate) to 4 decimal places?

Upvotes: 5

Views: 4543

Answers (2)

ChrisHax
ChrisHax

Reputation: 49

If you are attempting this in Kotlin Aman's answer will still work but you must use a type token rather than Double.class(or Double::class.java):

builder.registerTypeAdapter(object: TypeToken<Double>() {}.type, ...

Upvotes: 4

Aman Singh
Aman Singh

Reputation: 1104

Figured it out. Can use a type adapter:

GsonBuilder builder = new GsonBuilder();
builder.registerTypeAdapter(Double.class, (JsonSerializer<Double>) (src, typeOfSrc, context) -> {
    DecimalFormat df = new DecimalFormat("#.####");
    df.setRoundingMode(RoundingMode.CEILING);
    return new JsonPrimitive(Double.parseDouble(df.format(src)));
});
Gson gson = builder.create();

Upvotes: 7

Related Questions