Java Double Number Format formatDouble(double value)

Here you can find the source of formatDouble(double value)

Description

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

License

Open Source License

Parameter

Parameter Description
value the value to be formatted

Return

the formatted string

Declaration

public static String formatDouble(double value) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

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

    /**/* w  ww .  j ava 2 s  . co m*/
     * 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

  1. formatDouble(double val, int prec)
  2. formatDouble(double val, int precision)
  3. formatDouble(double value)
  4. formatDouble(double value)
  5. formatDouble(double value)
  6. formatDouble(double value, int decimals)
  7. formatDouble(final double value)
  8. formatDouble(final Object value)
  9. formatDouble(String value)