Java Double Number Format formatDouble(double d, int n)

Here you can find the source of formatDouble(double d, int n)

Description

Formats a double to a given number of digits past the decimal point and cuts the tailing zeroes

License

Open Source License

Parameter

Parameter Description
d number to be formatted
n number of digits after decimal point

Return

formatted string

Declaration

public static String formatDouble(double d, int n) 

Method Source Code

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

public class Main {
    /**/* w w  w  .j  a  v a  2 s .c o m*/
     * Formats a double to a given number of digits past the decimal point and
     * cuts the tailing zeroes
     * 
     * @param d
     *            number to be formatted
     * @param n
     *            number of digits after decimal point
     * @return formatted string
     */
    public static String formatDouble(double d, int n) {
        String s = String.format("%." + n + "f", d);

        int i = s.length() - 1;
        // cut tailing zeros
        while (s.charAt(i) == '0') {
            s = s.substring(0, i);
            i--;
        }

        // check if decimal point reached
        if (s.charAt(i) == '.')
            s = s.substring(0, i);

        return s;
    }
}

Related

  1. format(final double power)
  2. formatDouble(double d)
  3. formatDouble(double d)
  4. formatDouble(double d)
  5. formatDouble(double d, int n)
  6. formatDouble(double d, int n, String pad)
  7. formatDouble(double d, int precision)
  8. formatDouble(double inDouble, boolean inComma, int inCommaPos)
  9. formatDouble(double num, int width, int precision)