Example usage for java.text DecimalFormat DecimalFormat

List of usage examples for java.text DecimalFormat DecimalFormat

Introduction

In this page you can find the example usage for java.text DecimalFormat DecimalFormat.

Prototype

public DecimalFormat(String pattern) 

Source Link

Document

Creates a DecimalFormat using the given pattern and the symbols for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:Main.java

/**
 * Returns a formatted string representation of the number of bytes specified. The largest
 * suitable suffix up until GB will be used, with the returned value expressed to two 
 * decimal places.//  w  w w  . ja va2 s  . c  o m
 * @param bytes The number of bytes to be reported.
 * @return The specified number of bytes, formatted as a string, in bytes, KB, MB or GB.
 */
static public String formatBytes(long bytes) {

    double val = 0;
    String units = "";

    if (bytes < 1024) {
        val = bytes;
        units = "bytes";
    } else if (bytes < 1048576) {
        val = (bytes / 1024.0f);
        units = "KB";
    } else if (bytes < 1073741824) {
        val = (bytes / 1048576.0f);
        units = "MB";
    } else {
        val = (bytes / 1073741824.0f);
        units = "GB";
    }

    DecimalFormat df = new DecimalFormat("###.##");
    return df.format(val) + " " + units;

}

From source file:ch.admin.suis.msghandler.common.MessageType.java

/**
 * {@inheritDoc }
 */
@Override
public String toString() {
    return new DecimalFormat("####0").format(type);
}

From source file:eu.fbk.utils.lsa.util.AnvurTest.java

public static void main(String[] args) throws Exception {
    String logConfig = System.getProperty("log-config");
    if (logConfig == null) {
        logConfig = "log-config.txt";
    }// ww w  .ja  v a 2  s  .  co  m

    PropertyConfigurator.configure(logConfig);

    if (args.length != 8) {
        System.out.println(args.length);
        System.out.println(
                "Usage: java -mx2G eu.fbk.utils.lsa.util.AnvurTest root-lsa-en root-lsa-it threshold-lsa size-lsa dim-lsa idf-lsa in-file-tsv fields-tsv\n\n");
        System.exit(1);
    }

    //
    DecimalFormat dec = new DecimalFormat("#.00");

    File enUt = new File(args[0] + "-Ut");
    File enSk = new File(args[0] + "-S");
    File enr = new File(args[0] + "-row");
    File enc = new File(args[0] + "-col");
    File endf = new File(args[0] + "-df");
    File itUt = new File(args[1] + "-Ut");
    File itSk = new File(args[1] + "-S");
    File itr = new File(args[1] + "-row");
    File itc = new File(args[1] + "-col");
    File itdf = new File(args[1] + "-df");

    double threshold = Double.parseDouble(args[2]);
    int size = Integer.parseInt(args[3]);
    int dim = Integer.parseInt(args[4]);
    boolean rescaleIdf = Boolean.parseBoolean(args[5]);

    LSM enLsm = new LSM(enUt, enSk, enr, enc, endf, dim, rescaleIdf);
    LSM itLsm = new LSM(itUt, itSk, itr, itc, itdf, dim, rescaleIdf);

    File in = new File(args[6]);

    if (in.isFile()) {
        run(enLsm, itLsm, args[6], args[7]);
    } else if (in.isDirectory()) {
        FolderScanner fs = new FolderScanner(in);
        fs.setFiler(new TsvFilter());
        int count = 0;
        while (fs.hasNext()) {
            Object[] files = fs.next();
            System.out.println((count++) + " : " + files.length);
            for (int i = 0; i < files.length; i++) {

                String name = ((File) files[i]).getAbsolutePath();
                System.out.println(name);
                run(enLsm, itLsm, name, args[7]);
            } // end for i
        } // end while
    }

}

From source file:front.TestTable.java

public TestTable(Controller cont, int[][] response, float[] vec, float rango, int cantIntervalos) {

    controller = cont;//from  www.j  av a 2  s  . c  o  m
    contador = response.length;
    initComponents();

    DecimalFormat in = new DecimalFormat("0.00");
    DecimalFormat aleat = new DecimalFormat("0.0000");
    DecimalFormat c = new DecimalFormat("0.000");
    int contador = 0;
    int frecEsp = (int) vec.length / cantIntervalos;
    double rangoM;
    float[][] matrizIntervalos = new float[cantIntervalos][2];
    double[] estadisticoParcial = new double[cantIntervalos];
    DefaultTableModel tm = (DefaultTableModel) table.getModel();

    for (int i = 0; i < response.length; i++) {
        if (i == 0) {
            rangoM = rango;
            tm.addRow(new Object[] { "0.00 - " + in.format(rangoM), i, response[i][1], frecEsp,
                    c.format(estadisticoPrueba(response, frecEsp, i)) });
            contador++;
            matrizIntervalos[0][0] = 0;
            matrizIntervalos[0][1] = (float) rangoM;

        } else {
            if (contador == 1) {
                tm.addRow(new Object[] { in.format(rango) + " - " + in.format(rango + rango), i, response[i][1],
                        frecEsp, c.format(estadisticoPrueba(response, frecEsp, i)) });

                matrizIntervalos[i][0] = rango;
                matrizIntervalos[i][1] = (float) rango + rango;
                contador++;

            } else {
                tm.addRow(new Object[] {
                        in.format(rango * contador) + " - " + in.format((rango * contador) + rango), i,
                        response[i][1], frecEsp, c.format(estadisticoPrueba(response, frecEsp, i)) });
                matrizIntervalos[i][0] = rango * contador;
                matrizIntervalos[i][1] = (rango * contador) + rango;
                contador++;
            }

        }
    }

    if (frecEsp < 5) {
        DefaultTableModel tm2 = (DefaultTableModel) tablaFe.getModel();
        double estadisticoTotal = 0;
        int frecEspAcumulada = 0;
        int frecObsAcumulada = 0;
        int inicio = 0;
        float a = 0;

        for (int i = 0; i < tm.getRowCount(); i++) {
            frecEspAcumulada += (int) tm.getValueAt(i, 2);
            frecObsAcumulada += (int) tm.getValueAt(i, 1);

            if (frecEspAcumulada >= 5) {
                estadisticoParcial[i] += estadisticoPrueba2(frecObsAcumulada, (int) frecEspAcumulada);
                tm2.addRow(new Object[] {
                        in.format(matrizIntervalos[inicio][0]) + " - " + in.format(matrizIntervalos[i][1]),
                        (int) frecObsAcumulada, frecEspAcumulada, c.format(estadisticoParcial[i]) });
                a = matrizIntervalos[inicio][0];
                inicio = i + 1;

                frecEspAcumulada = 0;
                frecObsAcumulada = 0;
            } else {
                if (i == tm.getRowCount() - 1) {
                    int filaAUnir = tm2.getRowCount() - 1;
                    //actualizo intervalo
                    tm2.setValueAt(in.format(a) + " - " + in.format(matrizIntervalos[i][1]), filaAUnir, 0);
                    //frec observada
                    tm2.setValueAt(frecObsAcumulada + (int) tm2.getValueAt(filaAUnir, 1), filaAUnir, 1);
                    //frec esperada
                    tm2.setValueAt(frecEspAcumulada + (int) tm2.getValueAt(filaAUnir, 2), filaAUnir, 2);

                    int frecObsUltima = (int) tm2.getValueAt(filaAUnir, 1);
                    int frecEspUltima = (int) tm2.getValueAt(filaAUnir, 2);

                    estadisticoParcial[i - 1] = estadisticoPrueba2(frecObsUltima, frecEspUltima);
                    tm2.setValueAt(estadisticoParcial[i - 1], filaAUnir, 3);
                    break;
                }
            }
        }

        for (int i = 0; i < estadisticoParcial.length; i++) {
            estadisticoTotal += estadisticoParcial[i];
        }
        txt_gradosNuevo.setText("" + gradosLibertad(tm2.getRowCount()));
        txt_estadisticoNuevo.setText("" + c.format(estadisticoTotal));
    }
    //para mostrar los valores generados
    String acum = "";
    for (int i = 0; i < vec.length; i++) {
        acum += "Valor " + (i + 1) + ": " + aleat.format(vec[i]) + ".\n";
    }
    txt_valoresGenerados.setText(acum);

    //para el calculo de mi estadistico de prueba total
    txt_estadistico.setText("" + c.format(estadisticoPruebaTotal(response, frecEsp)));
    txt_grados.setText("" + gradosLibertad(cantIntervalos));

    valoresGenerados = vec;
    this.cantIntervalos = cantIntervalos;
    agregarHistograma();

}

From source file:com.imagelake.earnings.Servlet_EarningsValues.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {/*from w ww  . j a  v a2s. co  m*/
        String uid = request.getParameter("uid");
        if (uid != null && !uid.equals("")) {

            uidd = Integer.parseInt(uid);

            PaymentPreferences pp = ppimp.getPendingEarning(uidd, 1);
            double pd = 00.00;
            double ad = 00.00;
            if (pp != null) {
                pd = pp.getAmount();
                DecimalFormat df1 = new DecimalFormat("#.##");
                pd = Double.valueOf(df1.format(pd));

            }

            SellerIncome sin = sidi.getSellerIncome(uidd);
            ad = sin.getTotal();
            DecimalFormat df = new DecimalFormat("#.##");
            ad = Double.valueOf(df.format(ad));

            double netamo = ad - pd;
            DecimalFormat df2 = new DecimalFormat("#.##");
            netamo = Double.valueOf(df2.format(netamo));

            JSONObject jo = new JSONObject();
            jo.put("pe", pd);
            jo.put("ab", ad);
            jo.put("ne", netamo);

            out.write("json=" + jo.toJSONString());
        }
    } catch (Exception e) {
        e.printStackTrace();

    }
}

From source file:fr.bde_eseo.eseomega.lacommande.model.LacmdCategory.java

public String getBeginPriceAsStr() {
    return " partir de " + new DecimalFormat("0.00").format(beginPrice) + "";
}

From source file:com.swcguild.springmvcwebapp.controller.FlooringController.java

@RequestMapping(value = "/flooring", method = RequestMethod.POST)
public String doPost(HttpServletRequest request, Model model) {

    try {//from   ww w.  ja va2  s .c om
        width = Double.parseDouble(request.getParameter("myWidth"));
        length = Double.parseDouble(request.getParameter("myLength"));
        myCost = request.getParameter("myCost");

        cost = Double.parseDouble(myCost);
        area = width * length;

        totalMatCost = area * cost;

        totalLabor = laborCost(area);

        quote = totalLabor + totalMatCost;

        DecimalFormat df = new DecimalFormat("#.00");

        model.addAttribute("area", df.format(area));
        model.addAttribute("totalMatCost", df.format(totalMatCost));
        model.addAttribute("totalLabor", df.format(totalLabor));
        model.addAttribute("quote", df.format(quote));
    } catch (NumberFormatException e) {
    }

    return "flooringResponse";
}

From source file:ca.sqlpower.dao.session.FormatConverter.java

public Format convertToComplexType(String convertFrom) throws ConversionException {

    //The patterns can contain the delimiter character.
    int firstSeparator = convertFrom.indexOf(DELIMITER);

    if (firstSeparator == -1) {
        throw new IllegalArgumentException("Cannot find the class type for the string " + convertFrom);
    }/*  ww  w  . j  av a 2  s .c  o  m*/

    String className = convertFrom.substring(0, firstSeparator);
    String pattern = convertFrom.substring(firstSeparator + 1);

    if (className.equals(DecimalFormat.class.getSimpleName())) {
        return new DecimalFormat(pattern);
    } else if (className.equals(SimpleDateFormat.class.getSimpleName())) {
        return new SimpleDateFormat(pattern);
    } else {
        throw new IllegalStateException(
                "Unknown class " + className + " to create a format on based on the pattern " + pattern);
    }
}

From source file:org.jfree.chart.demo.StackedBarDemo3.java

public StackedBarDemo3(String s) {
    super(s);/*from   ww w.java2 s.c o m*/
    DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
    defaultcategorydataset.addValue(1.0D, "Row 1", "Column 1");
    defaultcategorydataset.addValue(5D, "Row 1", "Column 2");
    defaultcategorydataset.addValue(3D, "Row 1", "Column 3");
    defaultcategorydataset.addValue(2D, "Row 2", "Column 1");
    defaultcategorydataset.addValue(3D, "Row 2", "Column 2");
    defaultcategorydataset.addValue(2D, "Row 2", "Column 3");
    JFreeChart jfreechart = ChartFactory.createStackedBarChart("StackedBarDemo3", "Category", "Value",
            defaultcategorydataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot categoryplot = (CategoryPlot) jfreechart.getPlot();
    StackedBarRenderer stackedbarrenderer = (StackedBarRenderer) categoryplot.getRenderer();
    stackedbarrenderer.setRenderAsPercentages(true);
    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    numberaxis.setLabel("Percentage");
    numberaxis.setNumberFormatOverride(new DecimalFormat("0.0%"));
    ChartPanel chartpanel = new ChartPanel(jfreechart, false);
    chartpanel.setPreferredSize(new Dimension(500, 270));
    setContentPane(chartpanel);
}

From source file:de.perdian.commons.lang.conversion.impl.converters.TestStringToNumberConverter.java

@Test
public void testConvertWithFormat() {
    StringToNumberConverter converter = new StringToNumberConverter(new DecimalFormat("00"));
    Assert.assertEquals(42, converter.convert("42").intValue());
}