Java Number Divide div(Class clazz, T a, T b)

Here you can find the source of div(Class clazz, T a, T b)

Description

div

License

Open Source License

Declaration

@SuppressWarnings("unchecked")
    public static <T extends Number> T div(Class<T> clazz, T a, T b) 

Method Source Code


//package com.java2s;
/*// w w  w . j  av a2 s . co  m
 * NumberUtils.java
 *
 * Copyright (C) 2010 Leo Osvald <leo.osvald@gmail.com>
 *
 * This file is part of YOUR PROGRAM NAME.
 * 
 * YOUR PROGRAM NAME is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * YOUR PROGRAM NAME 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 General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with YOUR PROGRAM NAME. If not, see <http://www.gnu.org/licenses/>.
 */

import java.math.BigDecimal;

public class Main {
    @SuppressWarnings("unchecked")
    public static <T extends Number> T div(Class<T> clazz, T a, T b) {
        if (clazz == Double.class)
            return (T) Double.valueOf(a.doubleValue() / b.doubleValue());
        if (clazz == Float.class)
            return (T) Float.valueOf(a.floatValue() / b.floatValue());
        if (clazz == Integer.class)
            return (T) Integer.valueOf(a.intValue() / b.intValue());
        if (clazz == BigDecimal.class)
            return (T) ((BigDecimal) a).divide((BigDecimal) b);
        return null;
    }

    @SuppressWarnings("unchecked")
    public static <T extends Number> T div(Class<T> clazz, T a, T b, T c, T... arr) {
        if (clazz == Double.class) {
            double r = a.doubleValue() / b.doubleValue() / c.doubleValue();
            for (T x : arr)
                r /= x.doubleValue();
            return (T) Double.valueOf(r);
        }
        if (clazz == Float.class) {
            float r = a.floatValue() / b.floatValue() / c.floatValue();
            for (T x : arr)
                r /= x.floatValue();
            return (T) Float.valueOf(r);
        }
        if (clazz == Integer.class) {
            int r = a.intValue() / b.intValue() / c.intValue();
            for (T x : arr)
                r /= x.intValue();
            return (T) Integer.valueOf(r);
        }
        if (clazz == BigDecimal.class) {
            BigDecimal r = ((BigDecimal) a).divide((BigDecimal) b).divide((BigDecimal) c);
            for (T x : arr) {
                r = r.divide((BigDecimal) x);
            }
            return (T) r;
        }
        return null;
    }
}

Related

  1. div(double a, double b, int len)
  2. div(double operand1, double operand2)
  3. div(double v1, double v2)
  4. div(Double v1, Double v2)