

package com.acme.util.utilities;

import java.math.BigDecimal;

import java.text.DecimalFormat;

import java.util.Random;

/**
 * <p>Title: MathUtility.java </p>
 * <p>Description: </p>
 *
 * @author MustafaY
 * @version 1.0, , Jul 24, 2008
 * @see
 * @since
 */
public class MathUtility
{
    public static double roundToNearest(double number)
    {
        return roundToNearestWithScale(number, 2);
    }

    /*
	 * BigDecimal constructor with double parameter return unpredictable results
	 * so conversion to string is used
	 */

    public static double roundToNearestWithScale(double number, int scale)
    {
        //BigDecimal temp = new BigDecimal(number);
        BigDecimal temp = new BigDecimal(Double.toString(number));
        temp = temp.setScale(scale, BigDecimal.ROUND_HALF_UP);

        return temp.doubleValue();
    }

    public static double roundUp(double number)
    {
        return roundUpWithScale(number, 0);
    }

    public static double roundUpWithScale(double number, int scale)
    {
        //BigDecimal temp = new BigDecimal(number);
        BigDecimal temp = new BigDecimal(Double.toString(number));
        temp = temp.setScale(scale, BigDecimal.ROUND_CEILING);

        return temp.doubleValue();
    }

    public static double roundDown(double number)
    {
        return roundDownWithScale(number, 0);
    }

    public static double roundDownWithScale(double number, int scale)
    {
        //BigDecimal temp = new BigDecimal(number);
        BigDecimal temp = new BigDecimal(Double.toString(number));
        temp = temp.setScale(scale, BigDecimal.ROUND_FLOOR);

        return temp.doubleValue();
    }

    public static double getDecimalPart(double number)
    {
        double roundedValue = roundDown(number);

        return number - roundedValue;
    }

    public static int convertStringToInt(String string)
    {
        return new BigDecimal(convertStringToDouble(string)).intValue();
    }

    public static long convertStringToLong(String string)
    {
        return (long)convertStringToDouble(string);
    }

    public static double convertStringToDouble(String stringValue)
    {
        return new Double(stringValue.replaceAll("[^\\.\\d-]", ""));
    }

    public static String formatNumber(double val, String mask)
    {
        int indexOfDot = -1;

        if ((indexOfDot = mask.indexOf(".")) > -1)
        {
            String intPart = mask.substring(0, indexOfDot + 1);
            String decimalPart = mask.substring(indexOfDot + 1).replaceAll("#", "0");

            mask = intPart + decimalPart;
        }

        DecimalFormat decimalFormat = new DecimalFormat(mask);
        return decimalFormat.format(val);
    }

    public static int getRandomNumber(int range)
    {
        Random randomGenerator = new Random();
        return randomGenerator.nextInt(range);
    }

}
