Java Float Number Format formatFloat(float num, int width, int precision)

Here you can find the source of formatFloat(float num, int width, int precision)

Description

format Float

License

CDDL license

Declaration

public final static String formatFloat(float 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 formatFloat(float num, int width, int precision) {
        return formatReal(String.valueOf(num), width, precision);
    }//  ww  w . j  a v  a  2s.  c  om

    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. formatFloat(double num)
  2. formatFloat(double number, int precision)
  3. formatFloat(double value, int decimals)
  4. formatFloat(float f)
  5. formatFloat(float input, int numDecimals)
  6. formatFloat(float val)
  7. formatFloat(String value)