Java BigDecimal Create toBigDecimal(final Object value)

Here you can find the source of toBigDecimal(final Object value)

Description

to Big Decimal

License

LGPL

Declaration

public static BigDecimal toBigDecimal(final Object value) 

Method Source Code

//package com.java2s;
//License from project: LGPL 

import java.lang.reflect.Array;
import java.math.BigDecimal;

import java.text.*;
import java.util.*;

public class Main {
    private static final int STYLE_NUMBER = 0;
    private static final int STYLE_CURRENCY = 1;
    private static final int STYLE_PERCENT = 2;
    private static final int STYLE_INTEGER = 4;

    public static BigDecimal toBigDecimal(final Object value) {
        try {//  ww  w  .j a  va 2 s  .  c o m
            final Number number = toNumber(value);
            return new BigDecimal(number.toString());
        } catch (Throwable ignored) {
        }
        return BigDecimal.ZERO;
    }

    /**
     * Attempts to convert an unidentified {@link Object} into a {@link Number},
     * just short of turning it into a string and parsing it.  In other words,
     * this will convert to {@link Number} from a {@link Number}, {@link Calendar},
     * or {@link Date}.  If it can't do that, it will get the string value and have
     * {@link #toNumber(String, String, Locale)} try to parse it using the
     * default Locale and format.
     *
     * @param obj - the object to convert
     */
    public static Number toNumber(final Object obj) {
        return toNumber(obj, true);
    }

    /**
     * Just like {@link #toNumber(Object)} except that you can tell
     * this to attempt parsing the object as a String by passing {@code true}
     * as the second parameter.  If you do so, then it will have
     * {@link #toNumber(String, String, Locale)} try to parse it using the
     * default Locale and format.
     */
    public static Number toNumber(Object obj, boolean handleStrings) {
        if (obj == null) {
            return null;
        }
        if (obj instanceof Number) {
            return (Number) obj;
        }
        if (obj instanceof Date) {
            return ((Date) obj).getTime();
        }
        if (obj instanceof Calendar) {
            Date date = ((Calendar) obj).getTime();
            return date.getTime();
        }
        if (handleStrings) {
            // try parsing with default format and locale
            return toNumber(obj.toString(), "default", Locale.getDefault());
        }
        return null;
    }

    /**
     * Converts a string to an instance of {@link Number} using the
     * specified format and {@link Locale} to parse it.
     *
     * @param value  - the string to convert
     * @param format - the format the number is in
     * @param locale - the {@link Locale}
     * @return the string as a {@link Number} or <code>null</code> if no
     *         conversion is possible
     * @see NumberFormat#parse
     */
    public static Number toNumber(String value, String format, Locale locale) {
        if (value == null || format == null || locale == null) {
            return null;
        }
        try {
            NumberFormat parser = getNumberFormat(format, locale);
            return parser.parse(value);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * Converts an object to an instance of {@link Number} using the
     * specified format and {@link Locale} to parse it, if necessary.
     *
     * @param value  - the object to convert
     * @param format - the format the number is in
     * @param locale - the {@link Locale}
     * @return the object as a {@link Number} or <code>null</code> if no
     *         conversion is possible
     * @see NumberFormat#parse
     */
    public static Number toNumber(Object value, String format, Locale locale) {
        // first try the easy stuff
        Number number = toNumber(value, false);
        if (number != null) {
            return number;
        }

        // turn it into a string and try parsing it
        return toNumber(String.valueOf(value), format, locale);
    }

    /**
     * Converts objects to String.
     * Null returns null, Arrays and Collections return their first value,
     * or null if they have no values.
     *
     * @param value the object to be turned into a String
     * @return the string value of the object or null if the value is null
     *         or it is an array whose first value is null
     */
    public static String toString(final Object value) {
        if (value instanceof String) {
            return (String) value;
        }
        if (value == null) {
            return null;
        }
        if (value.getClass().isArray()) {
            if (Array.getLength(value) > 0) {
                // recurse on the first value
                return toString(Array.get(value, 0));
            }
            return null;
        }
        return String.valueOf(value);
    }

    /**
     * Returns the first value as a String, if any; otherwise returns null.
     *
     * @param values the Collection to be turned into a string
     * @return the string value of the first object in the collection
     *         or null if the collection is empty
     */
    public static String toString(Collection values) {
        if (values != null && !values.isEmpty()) {
            // recurse on the first value
            return toString(values.iterator().next());
        }
        return null;
    }

    /**
     * Returns a {@link NumberFormat} instance for the specified
     * format and {@link Locale}.  If the format specified is a standard
     * style pattern, then a number instance
     * will be returned with the number style set to the
     * specified style.  If it is a custom format, then a customized
     * {@link NumberFormat} will be returned.
     *
     * @param format the custom or standard formatting pattern to be used
     * @param locale the {@link Locale} to be used
     * @return an instance of {@link NumberFormat}
     * @see NumberFormat
     */
    public static NumberFormat getNumberFormat(String format, Locale locale) {
        if (format == null || locale == null) {
            return null;
        }

        NumberFormat nf = null;
        int style = getNumberStyleAsInt(format);
        if (style < 0) {
            // we have a custom format
            nf = new DecimalFormat(format, new DecimalFormatSymbols(locale));
        } else {
            // we have a standard format
            nf = getNumberFormat(style, locale);
        }
        return nf;
    }

    /**
     * Returns a {@link NumberFormat} instance for the specified
     * number style and {@link Locale}.
     *
     * @param numberStyle the number style (number will be ignored if this is
     *                    less than zero or the number style is not recognized)
     * @param locale      the {@link Locale} to be used
     * @return an instance of {@link NumberFormat} or <code>null</code>
     *         if an instance cannot be constructed with the given
     *         parameters
     */
    public static NumberFormat getNumberFormat(int numberStyle, Locale locale) {
        try {
            NumberFormat nf;
            switch (numberStyle) {
            case STYLE_NUMBER:
                nf = NumberFormat.getNumberInstance(locale);
                break;
            case STYLE_CURRENCY:
                nf = NumberFormat.getCurrencyInstance(locale);
                break;
            case STYLE_PERCENT:
                nf = NumberFormat.getPercentInstance(locale);
                break;
            case STYLE_INTEGER:
                nf = NumberFormat.getIntegerInstance(locale);
                break;
            default:
                // invalid style was specified, return null
                nf = null;
            }
            return nf;
        } catch (Exception suppressed) {
            // let it go...
            return null;
        }
    }

    /**
     * Checks a string to see if it matches one of the standard
     * NumberFormat style patterns:
     * number, currency, percent, integer, or default.
     * if it does it will return the integer constant for that pattern.
     * if not, it will return -1.
     *
     * @param style the string to be checked
     * @return the int identifying the style pattern
     * @see NumberFormat
     */
    public static int getNumberStyleAsInt(String style) {
        // avoid needlessly running through all the string comparisons
        if (style == null || style.length() < 6 || style.length() > 8) {
            return -1;
        }
        if (style.equalsIgnoreCase("default")) {
            //NOTE: java.text.NumberFormat returns "number" instances
            //      as the default (at least in Java 1.3 and 1.4).
            return STYLE_NUMBER;
        }
        if (style.equalsIgnoreCase("number")) {
            return STYLE_NUMBER;
        }
        if (style.equalsIgnoreCase("currency")) {
            return STYLE_CURRENCY;
        }
        if (style.equalsIgnoreCase("percent")) {
            return STYLE_PERCENT;
        }
        if (style.equalsIgnoreCase("integer")) {
            return STYLE_INTEGER;
        }
        // ok, it's not any of the standard patterns
        return -1;
    }
}

Related

  1. nullToBigDecimalZero(final Object obj)
  2. nullToZero(BigDecimal decimal)
  3. nullToZero(BigDecimal num)
  4. toBig(Object o)
  5. toBigDecimal(final Object o)
  6. toBigDecimal(Object o)
  7. toBigDecimal(Object obj)
  8. toBigDecimal(String bigDecimal)
  9. toBigDecimal(String text)