Format the given double with four digits precision, but leave it without a decimal point. - Java java.lang

Java examples for java.lang:double Format

Description

Format the given double with four digits precision, but leave it without a decimal point.

Demo Code


//package com.java2s;

public class Main {
    private static final double EPSILON = 0.0001;

    /**//from  w w  w. j av a2s  .com
     * Format the given double with four digits precision, but leave it without a decimal point.
     * if it is a round value
     * @param value the value to be formatted
     * @return the formatted string
     */
    public static String formatDouble(double value) {
        if (equalsEps(Math.round(value), value)) {
            return Long.toString(Math.round(value));
        }
        return Double.toString(Math.round(value * 10000.0) / 10000.0);
    }

    /**
     * Checks the the given doubles if they are equals - which means they are closer than a 
     * predefined epsilon value, because comparing two doubles directly is a bad practice.
     * @param a one of the values to be checked
     * @param b the other value to be checked
     * @return true if the two values are close enough to call them equals
     */
    public static boolean equalsEps(double a, double b) {
        return Math.abs(a - b) < EPSILON;
    }
}

Related Tutorials