02-注解定制Double精度位数

image-20210218161045094

注解定制Double精度位数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.Objects;

/**
* 定制Double序列化格式
*
* @author Jerry
* @date 2021-08-20
*/
@Slf4j
public class DoubleSerialize extends JsonSerializer {

private final DecimalFormat df = new DecimalFormat("0.0");

@Override
public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
if (Objects.nonNull(o)) {
//四舍五入
df.setRoundingMode(RoundingMode.HALF_UP);
String result = df.format(o);
jsonGenerator.writeNumber(Double.parseDouble(result));
log.info("转换数字:" + Double.parseDouble(result));
} else {
jsonGenerator.writeNumber(Double.valueOf(0));
}
}
}
1
2
3
@ApiModelProperty(value = "试卷总分")
@JsonSerialize(using = DoubleSerialize.class)
private Double paperScoreTotal;

image-20220110215830845


02-注解定制Double精度位数
https://janycode.github.io/2021/08/22/02_编程语言/01_Java/01_JavaSE/09_注解开发/02-注解定制Double精度位数/
作者
Jerry(姜源)
发布于
2021年8月22日
许可协议