package com.util;

import java.math.BigDecimal;

/**
 * @author Administrator
 */
public class NumberUtils {

    private static final String THOUSAND_UNIT = "k";
    private static final String MILLION_UNIT = "w";
    private static final String BILLION_UNIT = "e";
    private static final BigDecimal ONE_HUNDRED_THOUSAND = new BigDecimal(100000);
    private static final BigDecimal ONE_HUNDRED_MILLION = new BigDecimal(100000000);
    private static final BigDecimal TEN_THOUSAND = new BigDecimal(10000);
    private static final BigDecimal THOUSAND = new BigDecimal(1000);

    /**
     * 将数字转换成以万为单位或者以亿为单位，因为在前端数字太大显示有问题
     * @param str
     * @return
     */
    public static String amountConversion(int str){
        BigDecimal amount = new BigDecimal(str);
        if (amount.abs().compareTo(THOUSAND) < 0) {
            //如果小于1千
            return amount.stripTrailingZeros().toPlainString();
        }
        if (amount.abs().compareTo(TEN_THOUSAND) < 0) {
            //如果小于1万
            return amount.divide(THOUSAND, 0, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + THOUSAND_UNIT;
        }
        if (amount.abs().compareTo(ONE_HUNDRED_MILLION) < 0) {
            //小于1亿
            return amount.divide(TEN_THOUSAND, 0, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + MILLION_UNIT;
        }
        return amount.divide(ONE_HUNDRED_MILLION, 0, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + BILLION_UNIT;
    }

//    public static void main(String[] args) {
//        System.out.println(amountConversion(153));
//        System.out.println(amountConversion(7791));
//        System.out.println(amountConversion(54314));
//        System.out.println(amountConversion(291764245));
//    }

    /**
     * 将数字转换成以亿为单位
     * @param amount
     * @return
     */
    public static Double amountConversionBillion(BigDecimal amount){
        if (amount == null) {
            return null;
        }
        return amount.divide(ONE_HUNDRED_MILLION, 2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().doubleValue();
    }
}
