java金额转换

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

这样数据库在设计的时候金额就直接存储整型数据类型,前端可以将金额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(((Integer) t).intValue());
}
else if(t instanceof Long){
amount = new BigDecimal(((Long) t).intValue());
}
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;
}
}

@RestController
public class Demo {

@RequestMapping("/test")
public TestVo testMoneyConvert(){
TestVo vo=new TestVo();
vo.setId(1);
vo.setMoney(123);
return vo;
}
}

//结果展示:

 


猜你喜欢

转载自www.cnblogs.com/dinghua001/p/9662090.html
今日推荐