java金额转换

喜你入骨 提交于 2020-02-27 05:12:17

 

像商品价格,订单,结算都会涉及到一些金额的问题,为了避免精度丢失通常会做一些处理,常规的系统中金额一般精确到小数点后两位,也就是分;

这样数据库在设计的时候金额就直接存储整型数据类型,前端可以将金额X100以分为单位传给后端,后端进行一系列逻辑处理后要以元为单位返回前端直接展示,

这时候就可以定义一个简单的处理工具来转换:

public class MoneyConvert<T> {  //分转换为元,返回string类型    public  String centToDollarForString(T t){        if (t == null) {            return "0";        } else {            BigDecimal amount = getBigDecimal(t);            amount = amount.divide(new BigDecimal(100));            return amount.toString();        }    }  //分转换为元,返回double类型    public Double centToDollarForDouble(T t){        if (t == null) {            return 0D;        } else {            BigDecimal amount = getBigDecimal(t);            amount = amount.divide(new BigDecimal(100));            return amount.doubleValue();        }    }
private BigDecimal getBigDecimal(T t) {    BigDecimal amount;    if(t instanceof Integer){        amount = new BigDecimal(t.toString());    }    else if(t instanceof Long){        amount = new BigDecimal(t.toString());    }    else if(t instanceof String){        amount=new BigDecimal(t.toString());    }    else{        throw new RuntimeException(String.format("不支持的数据类型,%s",t.getClass()));    }    return amount;}
}//转换类
public class IntegerCentToStringDollar extends JsonSerializer<Integer> {    @Override    public void serialize(Integer value, JsonGenerator gen, SerializerProvider serializers) throws IOException, JsonProcessingException {        gen.writeNumber(new MoneyConvert<Integer>().centToDollarForString(value));    }}
import com.blogs.common.utils.IntegerCentToStringDollar;import com.fasterxml.jackson.databind.annotation.JsonSerialize;//在需要处理的字段上加上注解@JsonSerialize(using = IntegerCentToStringDollar.class)public class TestVo {    private Integer id;    @JsonSerialize(using = IntegerCentToStringDollar.class)    private Integer money;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public Integer getMoney() {        return money;    }    public void setMoney(Integer money) {        this.money = money;    }}
@RestControllerpublic class Demo {    @RequestMapping("/test")    public TestVo testMoneyConvert(){        TestVo vo=new TestVo();        vo.setId(1);        vo.setMoney(123);        return vo;    }}//结果展示:

 



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!