前端需要保留2位小数,即使小数点后是 0 也需要显示;
1、使用@JsonSerialize输出数据保留两位小数,创建一个BigDecimal格式化工具
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;import java.io.IOException;
import java.math.BigDecimal;
public class BigDecimalSerialize extends JsonSerializer<BigDecimal> {@Overridepublic void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {if (value != null && !"".equals(value)) {gen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_DOWN) + "");} else {gen.writeString(value + "");}}
}
2、在返回的实体类对应的属性上加上注解:
@JsonSerialize(using = BigDecimalSerialize.class)
private BigDecimal totalCost;
参考:https://juejin.im/post/5c91ad28e51d4574ed4ee0a3