Java Double Number Format format(Double decimal)

Here you can find the source of format(Double decimal)

Description

Attempts to format a Double to a String to the #DEFAULT_PRECISION .

License

Apache License

Parameter

Parameter Description
decimal the decimal, allows null

Return

the formatted decimal String or null

Declaration

public static String format(Double decimal) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    public static final int DEFAULT_PRECISION = 3;

    /**//from   w ww.j  a va 2  s .  c  o  m
     * Attempts to format a Double to a String to the {@link #DEFAULT_PRECISION}. If the 
     * <tt>decimal</tt> is null, null is returned.
     * @param decimal the decimal, allows null
     * @return the formatted decimal String or null
     */
    public static String format(Double decimal) {
        return format(decimal, DEFAULT_PRECISION);
    }

    /**
     * Attempts to format a Double to a String to <tt>toDecimalPlace</tt> decimal places. If the 
     * <tt>decimal</tt> is null, null is returned.
     * @param decimal the decimal, allows null
     * @param toDecimalPlace the expected amount of decimals, greater than or equal to 0
     * @return the formatted decimal String or null
     * @throws NumberFormatException when the <tt>toDecimalPlace</tt> is less than 0
     */
    public static String format(Double decimal, int toDecimalPlace) {
        return format(decimal, toDecimalPlace, null);
    }

    /**
     * Attempts to format a Double to a String to <tt>toDecimalPlace</tt> decimal places. If the 
     * <tt>decimal</tt> is null, <tt>returnOnNull</tt> is returned.
     * @param decimal the decimal, allows null
     * @param toDecimalPlace the expected amount of decimals, greater than or equal to 0
     * @param returnOnNull the String value to retunr if the Decimal is null
     * @return the formatted decimal String or null
     * @throws NumberFormatException when the <tt>toDecimalPlace</tt> is less than 0
     */
    public static String format(Double decimal, int toDecimalPlace, Double returnOnNull) {
        if (toDecimalPlace < 0) {
            throw new NumberFormatException();
        }

        if (decimal == null) {
            if (returnOnNull == null) {
                return null;
            }
            decimal = returnOnNull;
        }

        return String.format("%1$,." + toDecimalPlace + "f", decimal);
    }
}

Related

  1. doubleFormat(double d)
  2. doubleFormat(double number)
  3. doubleFormat(double val, boolean hiRes)
  4. format(double b)
  5. format(double d, int decimals)
  6. format(double num, int n)
  7. format(double number)
  8. format(Double number)
  9. format(double number, int nums)