package com.ms.api.util;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.DecimalFormat;

public class DoubleValueSerializer implements ObjectSerializer {

    @Override
    public void write(JSONSerializer jsonSerializer, Object o, Object fieldName, Type type, int i) throws IOException {
        SerializeWriter out = jsonSerializer.out;
        Double value = (Double) o;
        String text = doubleTrans(noZeros(value));
        if (text.contains(".")) {
            out.writeDouble(Double.parseDouble(text), true);
        } else {
            out.writeInt(Integer.parseInt(text));
        }
    }

    private Double noZeros(Double num) {
        BigDecimal value = new BigDecimal(num);
        //去除多余0
        BigDecimal noZeros = value.stripTrailingZeros();
        //BigDecimal => double
        return noZeros.doubleValue();
    }

    private String doubleTrans(double d){
        double eps = 1e-10;
        //判断是否为整数
        if(d-Math.floor(d) < eps){
            return String.valueOf((long)d);
        }
        DecimalFormat df = new DecimalFormat("#.#####");
        return df.format(d);
    }
}
