google / google/gson

00 as decimal places when serialize Double

Open
#1,769 3 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Java
Stars
24.2k
Forks
4.5k
Avg merge
6d 4h
Merged PRs (30d)
12

Description

Hi team,

For a specific reason, I want 2 decimal places for my double when serializing into JSON.
Something like:

9900 --> 9900.00
9900.0 --> 9900.00
9900.1234 --> 9900.12

My best result so far:

9900 --> 9900.0
9900.0 --> 9900.0
9900.1234 --> 9900.12

My DoubleAdapter.java, please advice. Thanks a lot!

```
class DoubleAdapter extends TypeAdapter {

@Override
public void write(JsonWriter jsonWriter, Double aDouble) throws IOException {
DecimalFormat df = new DecimalFormat("0.00");
jsonWriter.value(Double.valueOf(df.format(aDouble)));
}

@Override
public Double read(JsonReader jsonReader) throws IOException {
return jsonReader.nextDouble();
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.