Divide two numbers - Java java.lang

Java examples for java.lang:Number

Description

Divide two numbers

Demo Code

/*/*from   ww w. j  a  v a2s .c  om*/
 * 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
 */
//package com.java2s;

public class Main {
    public static void main(String[] argv) throws Exception {
        Number n1 = new Integer(2);
        Number n2 = new Integer(2);
        System.out.println(divide(n1, n2));
    }

    /**
     * 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 Tutorials