Java Fraction Format format(Double d, int digit)

Here you can find the source of format(Double d, int digit)

Description

Formats a double to string.

License

LGPL

Parameter

Parameter Description
d double to be formatted
digit digits to be kept, must be greater than 0

Return

formatted string result

Declaration

public static String format(Double d, int digit) 

Method Source Code


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

import java.text.DecimalFormat;

public class Main {
    /**/*from w  w  w  . ja  va2  s  . c  om*/
     * Formats a double to string.
     * 
     * @param d
     *            double to be formatted
     * @param digit
     *            digits to be kept, must be greater than 0
     * 
     * @return formatted string result
     */
    public static String format(Double d, int digit) {
        if (d == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        sb.append("#");

        for (int i = 0; i < digit; i++) {
            if (i == 0) {
                sb.append(".");
            }
            sb.append("#");
        }

        DecimalFormat df = new DecimalFormat(sb.toString());
        return df.format(d);
    }

    /**
     * Formats a double to string.
     * 
     * @param d
     *            double to be formatted
     * @param digit
     *            digits to be kept, must be greater than 0
     * 
     * @return formatted string result
     */
    public static String format(Double d, int digit, boolean kiloDelimitted) {
        if (d == null) {
            return "";
        }

        StringBuffer sb = new StringBuffer();
        if (kiloDelimitted) {
            sb.append("#,###");
        } else {
            sb.append("#");
        }

        for (int i = 0; i < digit; i++) {
            if (i == 0) {
                sb.append(".");
            }
            sb.append("#");
        }

        DecimalFormat df = new DecimalFormat(sb.toString());
        return df.format(d);
    }
}

Related

  1. format(double d)
  2. format(double d)
  3. format(double d, DecimalFormat unitFormatter)
  4. format(double d, java.text.NumberFormat format)
  5. format(double degrees)
  6. format(double input, String format)
  7. format(double n)