Java String Sub String substract(Number n1, Number n2)

Here you can find the source of substract(Number n1, Number n2)

Description

Substract two numbers

License

Open Source License

Declaration

public static Number substract(Number n1, Number n2) 

Method Source Code

//package com.java2s;
/*/*  ww w  . j  a  v a2  s . co m*/
 * This file is part of FFMQ.
 *
 * FFMQ is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * FFMQ is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with FFMQ; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

public class Main {
    /**
     * Substract two numbers
     */
    public static Number substract(Number n1, Number n2) {
        Class<?> type = getComputationType(n1, n2);
        Number val1 = convertTo(n1, type);
        Number val2 = convertTo(n2, type);

        if (type == Long.class)
            return Long.valueOf(val1.longValue() - val2.longValue());

        return new Double(val1.doubleValue() - val2.doubleValue());
    }

    private static Class<?> getComputationType(Number n1, Number n2) {
        Class<?> type1 = n1.getClass();
        Class<?> type2 = n2.getClass();
        if (isIntegerType(type1) && isIntegerType(type2))
            return Long.class;
        else
            return Double.class;
    }

    private static Number convertTo(Number n, Class<?> type) {
        Class<?> baseType = n.getClass();
        if (baseType == type)
            return n;

        if (type == Long.class)
            return Long.valueOf(n.longValue());
        return new Double(n.doubleValue());
    }

    private static boolean isIntegerType(Class<?> type) {
        return type == Byte.class || type == Short.class || type == Integer.class || type == Long.class;
    }
}

Related

  1. substr(String what, int begin, int end)
  2. substr(StringBuffer buf)
  3. substract(double[] a, double[] b)
  4. substract(double[] a, double[] b)
  5. substract(int[] array1, int[] array2)
  6. substraction2(double[] a, double[] b)
  7. substractPrefixPostfix(Object obj, String prefix, String suffix)
  8. subStrBeforeDotNotIncludeDot(String str)
  9. subStrByBytes(String str, int len, String tail)