package com.yintn.cbms.basicinfo.api.utils; import lombok.experimental.UtilityClass; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Optional; @UtilityClass public class BigDecimalUtil { public BigDecimal add(Object i, Object j) { return objectToBigDecimal(i).add(objectToBigDecimal(j)); } public BigDecimal subtract(Object i, Object j) { return objectToBigDecimal(i).subtract(objectToBigDecimal(j)); } public BigDecimal multiply(Object i, Object j) { return objectToBigDecimal(i).multiply(objectToBigDecimal(j)); } public BigDecimal divide(Object i, Object j) { return objectToBigDecimal(i).divide(objectToBigDecimal(j),2, RoundingMode.HALF_UP); } public BigDecimal objectToBigDecimal(Object value) { BigDecimal ret = null; if (value != null) { if (value instanceof BigDecimal) { ret = (BigDecimal) value; } else if (value instanceof String) { ret = new BigDecimal((String) value); } else if (value instanceof BigInteger) { ret = new BigDecimal((BigInteger) value); } else if (value instanceof Number) { ret = BigDecimal.valueOf(((Number) value).doubleValue()); } else { throw new ClassCastException("Not possible to coerce [" + value + "] from class " + value.getClass() + " into a BigDecimal."); } } if (ret != null) { ret = ret.setScale(2); } return ret; } public BigDecimal objectToBigDecimal1(Object object){ Object o = Optional.ofNullable(object).orElse(BigDecimal.ZERO); return new BigDecimal(String.valueOf(o)); } }
标签:value,BigDecimal,Object,ret,objectToBigDecimal,BigDecimalUtil,工具,public From: https://www.cnblogs.com/chenTo/p/17930015.html