Java Double Number Format formatDouble(double num, int width, int precision)

Here you can find the source of formatDouble(double num, int width, int precision)

Description

format Double

License

CDDL license

Declaration

public final static String formatDouble(double num, int width, int precision) 

Method Source Code

//package com.java2s;
//License from project: CDDL license 

public class Main {
    final static String spaces = new String("                                            ");

    public final static String formatDouble(double num, int width, int precision) {
        return formatReal(String.valueOf(num), width, precision); // bad for 7.6e-05 or other smallnums !?
    }/*from   w  w  w. j  a v  a  2s  .co  m*/

    public static String formatReal(String s, int width, int precision) {
        int dec = s.indexOf('.');
        if (dec > 0) {
            int len = s.length();
            while (len > dec && s.charAt(len - 1) == '0')
                len--; // chop trailing 00
            if (len - 1 == dec || precision == 0)
                len = dec; // drop .
            else if (precision > 0) {
                dec += precision + 1;
                if (dec < len)
                    len = dec;
            }
            s = s.substring(0, len);
        }
        return formatString(s, width);
    }

    public static String formatString(String s, int width) {
        int len = s.length();
        if (width > len)
            s = spaces.substring(0, width - len) + s;
        else if (-width > len)
            s = s + spaces.substring(0, (-width) - len);
        return s;
    }
}

Related

  1. formatDouble(double d, int n)
  2. formatDouble(double d, int n)
  3. formatDouble(double d, int n, String pad)
  4. formatDouble(double d, int precision)
  5. formatDouble(double inDouble, boolean inComma, int inCommaPos)
  6. FormatDouble(double p_value, int p_numberOfDecimalPlaces)
  7. formatDouble(double source, int decimals, int precision)
  8. formatDouble(double v, int decimalPlaces)
  9. formatDouble(double val)