Java Number Multiply multiply(Number n1, Number n2)

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

Description

Multiply two numbers

License

Open Source License

Declaration

public static Number multiply(Number n1, Number n2) 

Method Source Code

//package com.java2s;
/*/*from  w w w  .  j av a 2  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 {
    /**
     * Multiply two numbers
     */
    public static Number multiply(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. multiply(int a, int b)
  2. multiply(int x, int y)
  3. multiply(Number a, Number b)
  4. multiply(Number a, Number b, Class cl)
  5. multiply(Number n1, Number n2)
  6. multiply(V1 value1, V2 value2)
  7. multiplyForLong(final Number operand1, final int operand2)
  8. multiplyLongs(Long a, Long b)
  9. multiplyNumbers(Number a, Number b)