Java Number Compare compare(final Number x, final Number y)

Here you can find the source of compare(final Number x, final Number y)

Description

Compare two numbers of arbitrary data types

License

Apache License

Declaration

public static int compare(final Number x, final Number y) 

Method Source Code

//package com.java2s;
/**/* w  ww  .  ja  va2s  .c om*/
 * Copyright Notice
 *
 * This is a work of the U.S. Government and is not subject to copyright 
 * protection in the United States. Foreign copyrights may apply.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.math.BigDecimal;

public class Main {
    /**
     * Compare two numbers of arbitrary data types
     */
    public static int compare(final Number x, final Number y) {
        if (isSpecial(x) || isSpecial(y)) {
            return Double.compare(x.doubleValue(), y.doubleValue());
        } else {
            return toBigDecimal(x).compareTo(toBigDecimal(y));
        }
    }

    private static boolean isSpecial(final Number x) {
        boolean specialDouble = x instanceof Double && (Double.isNaN((Double) x) || Double.isInfinite((Double) x));
        boolean specialFloat = x instanceof Float && (Float.isNaN((Float) x) || Float.isInfinite((Float) x));
        return specialDouble || specialFloat;
    }

    private static BigDecimal toBigDecimal(final Number number) {
        if (number instanceof Integer || number instanceof Long) {
            return new BigDecimal(number.longValue());
        } else if (number instanceof Float || number instanceof Double) {
            return new BigDecimal(number.doubleValue());
        } else {
            throw new RuntimeException(
                    "Unexpected data type passed in to toBigDecimal (" + number.getClass() + ")");
        }
    }
}

Related

  1. compare(Object o1, Object o2)
  2. compareDoubleAgainstLong(double lhs, long rhs)
  3. compareDoublesWithTolerance(double aa, double bb, double tolerance)
  4. compareStringsAsNumbers(String s1, String s2, String op)