Java Number Divide divide(Number n1, Number n2)

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

Description

Divide two numbers

License

Open Source License

Declaration

public static Number divide(Number n1, Number n2) 

Method Source Code

//package com.java2s;
/*//w  w w .j  av  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 {
    /**
     * Divide two numbers
     */
    public static Number divide(Number n1, Number n2) {
        Class<?> type = getComputationType(n1, n2);
        Number val1 = convertTo(n1, type);
        Number val2 = convertTo(n2, type);

        if (type == Long.class) {
            if (val2.longValue() == 0)
                return null;
            return Long.valueOf(val1.longValue() / val2.longValue());
        }

        if (val2.doubleValue() == 0)
            return null;
        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. div(double v1, double v2, int scale)
  2. div(long v1, long v2)
  3. div(Object a, Object b)
  4. divide(Number a, Number b, Class cl)
  5. divide(Number n1, Number n2)
  6. divide(Number num1, Number num2)
  7. divide(Number numerator, Number denominator)
  8. divide(Number numerator, Number divisor)
  9. divideAndCeilWithBase(int number, int base)