package com.changhong.epc.rely.api.tool; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.math.NumberUtils; import java.math.BigDecimal; import java.text.DecimalFormat; import java.util.Objects; import java.util.Optional; @Slf4j public class CurrencyTool { // 美元 public static final String USD = "USD"; // 人民币 public static final String RMB = "RMB"; // 汇率转换后小数点限制 public static final DecimalFormat CURRENCY_TYPE = new DecimalFormat("#0.00"); /** * 兑换金额 * @param exchangeRate * @param money * @return */ public static String valueOf(String exchangeRate, Object money){ return Optional.ofNullable(money) .map(Object::toString) .filter(NumberUtils::isNumber) .filter(m->NumberUtils.isNumber(exchangeRate)) // .filter(m->!Objects.equals(money, "0")) // 转换BigDecimal .map(BigDecimal::new) // 乘汇率 .map(decimal->decimal.multiply(new BigDecimal(exchangeRate))) // 格式化保留两位小数 .map(CurrencyTool::format) // 为空返回原始金额 .orElse(Objects.toString(money)); } /** * 汇率单位计算 * @param exchangeRate * @param number * @return */ public static String divide(String exchangeRate, int number){ return Optional.ofNullable(exchangeRate) .filter(NumberUtils::isNumber) .map(BigDecimal::new) .map(decimal->decimal.divide(new BigDecimal(number))) .map(Object::toString) .orElse(exchangeRate); } public static String format(Object val){ return CURRENCY_TYPE.format(val); } public static void main(String... args){ System.out.println(CurrencyTool.valueOf(CurrencyTool.divide("16.2122", 100), "0")); System.out.println(CurrencyTool.divide("16.2122", 100)); } }