/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NumberUtil {
    public static boolean isNumber(final String value) {
        final Pattern p = Pattern.compile("([0-9]*)");
        final Matcher m = p.matcher(value);
        return m.matches();
    }

    public static Double precision(final Double d, final int decimalPlace) {
        BigDecimal bd = new BigDecimal(Double.toString(d));
        bd = bd.setScale(decimalPlace, RoundingMode.UP);
        return Double.valueOf(bd.doubleValue());
    }

    /**
     * Return the given size in bytes in a human readable format.
     *
     * @param size
     * @return
     */
    public static String humanByteSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"B", "kB", "MB", "GB", "TB", "EB"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
    }

    public static String humanSize(long size) {
        if (size <= 0) return "0";
        final String[] units = new String[]{"", "K", "M", "B", "T", "Q"};
        int digitGroups = (int) (Math.log10(size) / Math.log10(1000));
        return new DecimalFormat("#,##0.#").format(size / Math.pow(1000, digitGroups)) + units[digitGroups];
    }
}
