Java Number Sum sum(Number n1, Number n2)

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

Description

Sum two numbers

License

Open Source License

Declaration

public static Number sum(Number n1, Number n2) 

Method Source Code

//package com.java2s;
/*//from w w w . j  ava  2 s  . com
 * 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 {
    /**
     * Sum two numbers
     */
    public static Number sum(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. sum(int matrix1, int matrix2)
  2. sum(Iterable as)
  3. sum(Iterable iterable)
  4. sum(long space1, String space2)
  5. sum(long x, int c)
  6. Sum(Object in, int min, int max)
  7. sum(String fieldName)
  8. sum(String str11, String str22)
  9. sum0ToN(int n)