Java Fraction Format formatDouble(double inVal, int inNumPlaces, boolean pad)

Here you can find the source of formatDouble(double inVal, int inNumPlaces, boolean pad)

Description

format Double

License

Open Source License

Declaration

public static String formatDouble(double inVal, int inNumPlaces, boolean pad) 

Method Source Code

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

import java.text.*;

public class Main {
    public static String formatDouble(double inVal, int inNumPlaces, boolean pad) {
        if (inVal >= 1.0e35)
            return "    ----";
        int numPl = inNumPlaces;
        String valStr = new Double(inVal).toString();
        int expPlace = valStr.indexOf('E');
        if (expPlace > 0) {
            // number in scientific notation--get the exponent
            String exp = valStr.substring(expPlace, valStr.length());
            exp = exp.toLowerCase();//w  w  w. j a  va2  s.co  m
            exp = exp.substring(1, exp.length());
            int sign = exp.indexOf("-") >= 0 ? -1 : 1;
            numPl = Math.abs(Integer.valueOf(exp).intValue());
        }

        String frmt = null;
        if (numPl == 1)
            frmt = new String("0.0");
        else if (numPl == 2)
            frmt = new String("0.00");
        else if (numPl == 3)
            frmt = new String("0.000");
        else if (numPl == 4)
            frmt = new String("0.0000");
        else if (numPl == 5)
            frmt = new String("0.00000");
        else if (numPl == 6)
            frmt = new String("0.000000");

        StringBuffer out = new StringBuffer();
        try {
            DecimalFormat decFormatter = new DecimalFormat(frmt);
            decFormatter.format(inVal, out, new FieldPosition(0));
        } catch (Exception ex) {
            try {
                frmt = new String("###E##");
                DecimalFormat decFormatter = new DecimalFormat(frmt);
                decFormatter.format(inVal, out, new FieldPosition(0));
            } catch (Exception exx) {
                return new Double(inVal).toString();
            }
        }
        if (pad) {
            while (out.length() < 8)
                out.insert(0, ' ');
        }
        String str = new String(out);
        return str;
    }
}

Related

  1. formatDouble(Double d)
  2. formatDouble(double d, int maximumFractionDigits)
  3. formatDouble(Double d, NumberFormat format)
  4. formatDouble(Double doubleValue)
  5. formatDouble(Double in)
  6. formatDouble(Double num)
  7. formatDouble(double num)
  8. formatDouble(Double num)
  9. formatdouble(double number)