Java Decimal Format toDouble(Object obj, String pattern)

Here you can find the source of toDouble(Object obj, String pattern)

Description

to Double

License

Apache License

Declaration

public static Double toDouble(Object obj, String pattern) 

Method Source Code

//package com.java2s;
/*/*from www .j a v a 2s  .c  o m*/
 * Copyright 2004-2011 the Seasar Foundation and the Others.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */

import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.ObjectInputStream;

import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

import java.text.SimpleDateFormat;

import java.util.Calendar;
import java.util.Date;

import java.util.Locale;
import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

public class Main {
    private static final char[] ENCODE_TABLE = { 'A', 'B', 'C', 'D', 'E',
            'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
            'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c',
            'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
            'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0',
            '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' };
    private static final char PAD = '=';
    protected static Map<Locale, DecimalFormatSymbols> symbolsCache = new ConcurrentHashMap<Locale, DecimalFormatSymbols>();

    public static Double toDouble(Object obj) {
        return toDouble(obj, null);
    }

    public static Double toDouble(Object obj, String pattern) {
        if (obj == null) {
            return null;
        } else if (obj instanceof Double) {
            return (Double) obj;
        } else if (obj instanceof Number) {
            return Double.valueOf(((Number) obj).doubleValue());
        } else if (obj instanceof String) {
            return toDouble((String) obj);
        } else if (obj instanceof java.util.Date) {
            if (pattern != null) {
                return Double
                        .valueOf(createDateFormat(pattern).format(obj));
            }
            return Double.valueOf(((java.util.Date) obj).getTime());
        } else if (obj instanceof byte[]) {
            return toDouble(toSerializable((byte[]) obj)); // recursive
        } else {
            return toDouble(obj.toString());
        }
    }

    protected static Double toDouble(String str) {
        if (str == null || str.trim().length() == 0) {
            return null;
        }
        return new Double(normalize(str));
    }

    public static DateFormat createDateFormat(String pattern) { // as lenient
        return createDateFormat(pattern, false);
    }

    public static DateFormat createDateFormat(String pattern, boolean strict) {
        if (pattern == null) {
            String msg = "The argument 'pattern' should not be null!";
            throw new IllegalArgumentException(msg);
        }
        final SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        sdf.setLenient(!strict);
        return sdf;
    }

    public static Serializable toSerializable(byte[] bytes) {
        if (bytes == null) {
            return null;
        }
        try {
            final ByteArrayInputStream bais = new ByteArrayInputStream(
                    bytes);
            final ObjectInputStream ois = new ObjectInputStream(bais);
            try {
                return (Serializable) ois.readObject();
            } finally {
                ois.close();
            }
        } catch (Exception e) {
            String msg = "Failed to convert the object to binary: bytes.length="
                    + bytes.length;
            throw new IllegalStateException(msg, e);
        }
    }

    /**
     * Convert the object to the instance that is string. <br />
     * If the object is a byte array, encode as base64.
     * And if the object is a exception (throw-able), convert to stack-trace.
     * @param obj The parsed object. (NullAllowed)
     * @return The instance of string. (NullAllowed)
     */
    public static String toString(Object obj) {
        return toString(obj, null);
    }

    /**
     * Convert the object to the instance that is string. <br />
     * If the object is a byte array, encode as base64.
     * And if the object is a exception (throw-able), convert to stack-trace.
     * @param obj The parsed object. (NullAllowed)
     * @param pattern The pattern format to parse. (NullAllowed)
     * @return The instance of string. (NullAllowed)
     */
    public static String toString(Object obj, String pattern) {
        if (obj == null) {
            return null;
        } else if (obj instanceof String) {
            return (String) obj;
        } else if (obj instanceof Date) {
            return toStringFromDate((Date) obj, pattern);
        } else if (obj instanceof Number) {
            return toStringFromNumber((Number) obj, pattern);
        } else if (obj instanceof Calendar) {
            return toStringFromDate(((Calendar) obj).getTime(), pattern);
        } else if (obj instanceof byte[]) {
            return encodeAsBase64((byte[]) obj);
        } else if (obj instanceof Throwable) {
            return toStringStackTrace((Throwable) obj);
        } else {
            return obj.toString();
        }
    }

    protected static String normalize(String value) {
        return normalize(value, Locale.getDefault());
    }

    protected static String normalize(String value, Locale locale) {
        if (value == null) {
            return null;
        }
        final DecimalFormatSymbols symbols = getDecimalFormatSymbols(locale);
        final char groupingSep = symbols.getGroupingSeparator();
        final char decimalSep = symbols.getDecimalSeparator();
        final StringBuilder sb = new StringBuilder(20);
        for (int i = 0; i < value.length(); ++i) {
            char c = value.charAt(i);
            if (c == groupingSep) {
                continue;
            } else if (c == decimalSep) {
                c = '.';
            }
            sb.append(c);
        }
        return sb.toString();
    }

    protected static String toStringFromDate(Date value, String pattern) {
        if (value != null) {
            if (pattern != null) {
                return createDateFormat(pattern).format(value);
            }
            return value.toString();
        }
        return null;
    }

    protected static String toStringFromNumber(Number value, String pattern) {
        if (value != null) {
            if (pattern != null) {
                return createDecimalFormat(pattern).format(value);
            }
            return value.toString();
        }
        return null;
    }

    public static String encodeAsBase64(final byte[] inData) {
        if (inData == null || inData.length == 0) {
            return "";
        }
        int mod = inData.length % 3;
        int num = inData.length / 3;
        char[] outData = null;
        if (mod != 0) {
            outData = new char[(num + 1) * 4];
        } else {
            outData = new char[num * 4];
        }
        for (int i = 0; i < num; i++) {
            encode(inData, i * 3, outData, i * 4);
        }
        switch (mod) {
        case 1:
            encode2pad(inData, num * 3, outData, num * 4);
            break;
        case 2:
            encode1pad(inData, num * 3, outData, num * 4);
            break;
        }
        return new String(outData);
    }

    protected static String toStringStackTrace(Throwable t) {
        StringWriter sw = null;
        try {
            sw = new StringWriter();
            t.printStackTrace(new PrintWriter(sw));
            return sw.toString();
        } finally {
            if (sw != null) {
                try {
                    sw.close();
                } catch (IOException e) {
                }
            }
        }
    }

    protected static DecimalFormatSymbols getDecimalFormatSymbols(
            Locale locale) {
        DecimalFormatSymbols symbols = (DecimalFormatSymbols) symbolsCache
                .get(locale);
        if (symbols == null) {
            symbols = new DecimalFormatSymbols(locale);
            symbolsCache.put(locale, symbols);
        }
        return symbols;
    }

    public static DecimalFormat createDecimalFormat(String pattern) {
        return new DecimalFormat(pattern);
    }

    private static void encode(final byte[] inData, final int inIndex,
            final char[] outData, final int outIndex) {
        int i = ((inData[inIndex] & 0xff) << 16)
                + ((inData[inIndex + 1] & 0xff) << 8)
                + (inData[inIndex + 2] & 0xff);
        outData[outIndex] = ENCODE_TABLE[i >> 18];
        outData[outIndex + 1] = ENCODE_TABLE[(i >> 12) & 0x3f];
        outData[outIndex + 2] = ENCODE_TABLE[(i >> 6) & 0x3f];
        outData[outIndex + 3] = ENCODE_TABLE[i & 0x3f];
    }

    private static void encode2pad(final byte[] inData, final int inIndex,
            final char[] outData, final int outIndex) {
        int i = inData[inIndex] & 0xff;
        outData[outIndex] = ENCODE_TABLE[i >> 2];
        outData[outIndex + 1] = ENCODE_TABLE[(i << 4) & 0x3f];
        outData[outIndex + 2] = PAD;
        outData[outIndex + 3] = PAD;
    }

    private static void encode1pad(final byte[] inData, final int inIndex,
            final char[] outData, final int outIndex) {
        int i = ((inData[inIndex] & 0xff) << 8)
                + (inData[inIndex + 1] & 0xff);
        outData[outIndex] = ENCODE_TABLE[i >> 10];
        outData[outIndex + 1] = ENCODE_TABLE[(i >> 4) & 0x3f];
        outData[outIndex + 2] = ENCODE_TABLE[(i << 2) & 0x3f];
        outData[outIndex + 3] = PAD;
    }
}

Related

  1. string2Double(String s)
  2. strParaDouble(String s, double valorPadrao)
  3. to3DP(double number)
  4. toDecimalFromSexagesimalDegrees( final double sexagesimal)
  5. toDecimals(double d, int nrDecs)
  6. toDouble(String text)
  7. toDoubleObject(Object o)
  8. toDoubOriginOutPut(double d, int digitally)
  9. toEdmDouble(double value)