package org.jeecg.modules.adweb.common.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.NumberFormat;

/**
 * @author wfansh
 */
public class NumberUtil {

    private static final NumberFormat PERCENTAGE_FORMAT = NumberFormat.getPercentInstance();

    static {
        PERCENTAGE_FORMAT.setRoundingMode(RoundingMode.HALF_UP);
        // No grouping with ',' delimiter.
        PERCENTAGE_FORMAT.setGroupingUsed(false);
    }

    public static BigDecimal formatDecimal(double number, int fractionDigits) {
        BigDecimal decimal = new BigDecimal(number);
        return decimal.setScale(fractionDigits, RoundingMode.HALF_UP);
    }

    /**
     * {@link cn.hutool.core.util.NumberUtil#formatPercent(double, int)} 没有设置minimumFractionDigits
     */
    public static String formatPercentage(double number, int fractionDigits) {
        PERCENTAGE_FORMAT.setMinimumFractionDigits(fractionDigits);
        PERCENTAGE_FORMAT.setMaximumFractionDigits(fractionDigits);

        return PERCENTAGE_FORMAT.format(number);
    }

    /**
     * 安全除法，当分母为0返回0d，不抛出{@link ArithmeticException}
     *
     * @param x 强制转化为double
     * @param y
     * @return double类型结果
     */
    public static double safeDivide(double x, int y) {
        return y == 0 ? 0d : x / y;
    }
}
