package org.dromara.common.json.handler;

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;
import java.math.RoundingMode;
import java.util.Objects;

/**
 * BigDecimal 两位小数序列化
 *
 * @author shihongwei
 */
public class BigDecimalTwoDecimalSerializer extends JsonSerializer<BigDecimal> {

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (Objects.isNull(value)) {
            gen.writeNull();
        } else {
            // 保留两位小数，四舍五入
            String formatted = value.setScale(2, RoundingMode.HALF_UP).toPlainString();
            gen.writeString(formatted);
        }
    }
}
