Returns true if the given double is considered to be too close of a rounding value for the given scale. - Java java.lang

Java examples for java.lang:double

Description

Returns true if the given double is considered to be too close of a rounding value for the given scale.

Demo Code

/*//from  w w w. jav a 2  s.co m
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You 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.
 */
//package com.java2s;

public class Main {
    private static final double[] POWERS_OF_TEN_DOUBLE = new double[30];

    /**
     * Returns true if the given source is considered to be too close
     * of a rounding value for the given scale.
     *
     * @param source the source to round
     * @param scale the scale to round at
     * @return true if the source will be potentially rounded at the scale
     */
    private static boolean tooCloseToRound(double source, int scale) {
        source = Math.abs(source);
        long intPart = (long) Math.floor(source);
        double fracPart = (source - intPart) * tenPowDouble(scale);
        double decExp = Math.log10(source);
        double range = decExp + scale >= 12 ? .1 : .001;
        double distanceToRound1 = Math.abs(fracPart - Math.floor(fracPart));
        double distanceToRound2 = Math.abs(fracPart - Math.floor(fracPart)
                - 0.5);
        return distanceToRound1 <= range || distanceToRound2 <= range;
        // .001 range: Totally arbitrary range,
        // I never had a failure in 10e7 random tests with this value
        // May be JVM dependent or architecture dependent
    }

    private static double tenPowDouble(int n) {
        assert n >= 0;
        return n < POWERS_OF_TEN_DOUBLE.length ? POWERS_OF_TEN_DOUBLE[n]
                : Math.pow(10, n);
    }
}

Related Tutorials