java将数字单位化为万或者亿
1 public class NumberUtils { 2 3 private static final String MILLION_UNIT = "万"; 4 private static final String BILLION_UNIT = "亿"; 5 private static final BigDecimal ONE_HUNDRED_THOUSAND = new BigDecimal(100000); 6 private static final BigDecimal ONE_HUNDRED_MILLION = new BigDecimal(100000000); 7 private static final BigDecimal TEN_THOUSAND = new BigDecimal(10000); 8 9 /** 10 * 将数字转换成以万为单位或者以亿为单位,因为在前端数字太大显示有问题 11 * @param amount 12 * @return 13 */ 14 public static String amountConversion(BigDecimal amount){ 15 if (amount == null) { 16 return null; 17 } 18 if (amount.abs().compareTo(ONE_HUNDRED_THOUSAND) < 0) { 19 //如果小于10万 20 return amount.stripTrailingZeros().toPlainString(); 21 } 22 if (amount.abs().compareTo(ONE_HUNDRED_MILLION) < 0) { 23 //如果大于10万小于1亿 24 return amount.divide(TEN_THOUSAND, 4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + MILLION_UNIT; 25 } 26 return amount.divide(ONE_HUNDRED_MILLION, 4, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + BILLION_UNIT; 27 } 28 29 /** 30 * 将数字转换成以亿为单位 31 * @param amount 32 * @return 33 */ 34 public static Double amountConversionBillion(BigDecimal amount){ 35 if (amount == null) { 36 return null; 37 } 38 return amount.divide(ONE_HUNDRED_MILLION, 2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().doubleValue(); 39 } 40 }