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(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;
}
}

@RestController
public class Demo {

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

//結果展示:

 

 
        



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM