package com.inspect.base.core.utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

public class BigDecimalUtil {
    public static double round(double f) {
        return round(f, 1);
    }

    public static double round(double f, int remain) {
        BigDecimal bigDecimal = new BigDecimal(f);
        bigDecimal.setScale(1, 4);
        float v = bigDecimal.floatValue();
        String s = String.valueOf(v);
        if (s.contains(".") && s.substring(s.lastIndexOf(".") + 1).length() > remain) {
            s = s.substring(0, s.lastIndexOf(".") + remain + 1);
        }

        return Double.valueOf(s);
    }

    /**
     * 字符串转BigDecimal
     */
    public static BigDecimal toBigDecimal(String str) {
        if (str == null || str.isEmpty()) {
            return BigDecimal.ZERO;
        }

        try {
            String cleanStr = str.replace("%", "").trim();
            return new BigDecimal(cleanStr);
        } catch (Exception e) {
            return BigDecimal.ZERO;
        }
    }

    /**
     * 结果保留X位小数
     */
    public static String toOneDecimal(String str, int scale) {
        if (str == null || str.trim().isEmpty()) {
            return str;
        }
        try {
            return new BigDecimal(str.trim())
                    .setScale(scale, RoundingMode.DOWN)
                    .toString();
        } catch (NumberFormatException e) {
            return str;
        }
    }
}
