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:com.charts.TenYearChart.java

public TenYearChart(YStockQuote currentStock) throws ParseException {
    DateAxis domainAxis = new DateAxis("Date");
    NumberAxis rangeAxis = new NumberAxis("Price");
    CandlestickRenderer renderer = new CandlestickRenderer();
    XYDataset dataset = getDataSet(currentStock);

    XYPlot mainPlot = new XYPlot(dataset, domainAxis, rangeAxis, renderer);

    //Do some setting up, see the API Doc
    renderer.setBaseToolTipGenerator(//from  w w  w  . j  a v a2s  .  com
            new StandardXYToolTipGenerator(StandardXYToolTipGenerator.DEFAULT_TOOL_TIP_FORMAT,
                    new SimpleDateFormat("d-MMM-yyyy"), new DecimalFormat("0.00")));

    renderer.setDrawVolume(false);
    rangeAxis.setAutoRangeIncludesZero(false);

    domainAxis.setDateFormatOverride(new SimpleDateFormat("dd-MM-yy"));
    domainAxis.setTickMarkPosition(DateTickMarkPosition.MIDDLE);

    //Now create the chart and chart panel
    JFreeChart chart = new JFreeChart(currentStock.get_name(), null, mainPlot, false);

    chartPanel = new ChartPanel(chart);
    chartPanel.setPreferredSize(new Dimension(900, 400));

    XYPlot plot = (XYPlot) chart.getPlot();
    LegendTitle legend = new LegendTitle(plot);
    chart.addLegend(legend);
    chart.getLegend().setVisible(true);
    chart.getLegend().setPosition(RectangleEdge.BOTTOM);

    ValueAxis yAxis = (ValueAxis) plot.getRangeAxis();
    DateAxis xAxis = (DateAxis) plot.getDomainAxis();

    xAxis.setDateFormatOverride(new SimpleDateFormat("MMM y"));
    xAxis.setAutoTickUnitSelection(true);
    xAxis.setAutoRange(true);
    renderer.setAutoWidthFactor(0.5);
    renderer.setUpPaint(Color.green);
    renderer.setDownPaint(new Color(0xc0, 0x00, 0x00));
    renderer.setSeriesPaint(0, Color.BLACK);
    StandardXYItemRenderer renderer1 = new StandardXYItemRenderer();
    renderer1.setSeriesPaint(0, Color.BLUE);
    TimeSeries movingAverage30 = MovingAverage.createMovingAverage(close, "MA(30)", 30, 0);
    Double currMA30 = (Double) movingAverage30.getDataItem(movingAverage30.getItemCount() - 1).getValue();
    currMA30 = Math.round(currMA30 * 100.0) / 100.0;
    movingAverage30.setKey("MA(30): " + currMA30);
    TimeSeriesCollection collection = new TimeSeriesCollection();
    collection.addSeries(movingAverage30);
    plot.setDataset(1, collection);
    plot.setRenderer(1, renderer1);

    chartPanel.revalidate();
    chartPanel.repaint();
    chartPanel.revalidate();
    chartPanel.repaint();
}

From source file:com.eu.evaluation.server.eva.EvaluateExcutorTest.java

@Test
public void test() {
    double d = 0.987;
    logger.info("String.format = " + String.format("%.2f", d));
    DecimalFormat df = new DecimalFormat("*.00");
    logger.info("DecimalFormat = " + df.format(d));

    NumberFormat nf = NumberFormat.getNumberInstance();
    nf.setMaximumFractionDigits(2);/*  w w  w.j av  a2s  .c  o m*/
    logger.info("NumberFormat = " + nf.format(d));

    DecimalFormat formater = new DecimalFormat();
    formater.setMaximumFractionDigits(2);
    formater.setGroupingSize(0);
    formater.setRoundingMode(RoundingMode.FLOOR);
    logger.info("DecimalFormat = " + (formater.format(d)));
}

From source file:com.yahoo.platform.yui.coverage.report.FileReport.java

/**
 * Returns the percentage of lines called.
 * @return The percentage of lines called.
 * @throws org.json.JSONException//from   w w w  . ja  v a  2s.  com
 */
public double getCalledLinePercentage() throws JSONException {
    DecimalFormat twoDForm = new DecimalFormat("#.##");
    return Double
            .valueOf(twoDForm.format(((double) getCalledLineCount() / (double) getTotalLineCount()) * 100));
}

From source file:Emporium.Controle.ContrVpne.java

public static String lerVpne(FileItem item, int idCli, int idDepto, String nomeDepto, String nomeBD)
        throws UnsupportedEncodingException, IOException {
    DecimalFormat df = new DecimalFormat("0.00");

    String ret = "";

    String r_nome = "";
    String r_cpf_cnpj = "";
    String r_cep = "";
    String r_endereco = "";
    String r_numero = "";
    String r_bairro = "";
    String r_cidade = "";// se exiisteir o CEP no DNE
    String r_uf = "";

    String valor = "";

    String d_nome = "";
    String d_cpf_cnpj = "";
    String d_cep = "";
    String d_endereco = "";
    String d_numero = "";
    String d_bairro = "";

    String d_cidade = ""; // se existir na tabela movimentao
    String d_uf = "";

    String descricao = "";
    String sro = "";
    String data = "";

    BufferedReader le = new BufferedReader(new InputStreamReader(item.getInputStream(), "ISO-8859-1"));
    // LE UMA LINHA DO ARQUIVO PARA PULAR O CABEALHO   
    int lineNum = 1;
    while (le.ready()) {
        //LE UMA LINHA DO ARQUIVO 
        String aux = le.readLine();
        //ADICIONA CONTADOR DE LINHA

        if (lineNum == 1) {
            //remetente
            r_nome = aux.substring(38, 88).trim();
            r_cpf_cnpj = aux.substring(98, 112).trim();
            r_cep = aux.substring(112, 120).trim();
            r_endereco = aux.substring(130, 190).trim();
            r_numero = aux.substring(190, 198).trim();
            r_bairro = aux.substring(236, 276).trim();
            try {
                r_numero = Integer.parseInt(r_numero) + "";
            } catch (Exception ex) {
            }/*from  www  .j av  a2s.  co  m*/
        }
        if (lineNum >= 2 && aux.startsWith("DT")) {

            if (item.getName().contains("ValesPagos")) {
                //destinatario
                d_nome = aux.substring(26, 76).trim();
                d_cpf_cnpj = aux.substring(86, 106).trim();//ate106
                d_cep = aux.substring(106, 114).trim();
                d_endereco = aux.substring(124, 184).trim();
                d_numero = aux.substring(184, 230).trim();
                d_bairro = aux.substring(230, 270).trim();
                // String d_cidade;// se exiisteir o CEP no DNE
                // String d_uf;// se exiisteir o CEP no DNE

                sro = aux.substring(306, 319).trim();
                descricao = aux.substring(319, 369).trim();
                valor = aux.substring(298, 306).trim();
                data = aux.substring(369).trim();
            } else {
                //destinatario
                d_nome = aux.substring(26, 76).trim();
                d_cpf_cnpj = aux.substring(86, 100).trim();//ate106
                d_cep = aux.substring(100, 108).trim();
                d_endereco = aux.substring(118, 178).trim();
                d_numero = aux.substring(178, 224).trim();
                d_bairro = aux.substring(224, 264).trim();
                // String d_cidade;// se exiisteir o CEP no DNE
                // String d_uf;// se exiisteir o CEP no DNE

                sro = aux.substring(300, 313).trim();
                descricao = aux.substring(313, 363).trim();
                valor = aux.substring(292, 300).trim();
                data = aux.substring(363).trim();
            }

            try {
                d_numero = Integer.parseInt(d_numero) + "";
            } catch (Exception ex) {
            }
            try {
                valor = df.format((double) Integer.parseInt(valor) / 100) + "";
            } catch (Exception ex) {
            }

            data = data.substring(4, 8) + "-" + data.substring(2, 4) + "-" + data.substring(0, 2);

            Movimentacao mv = getConsultaBySRO(sro, nomeBD);
            if (mv != null) {
                d_uf = mv.getId();// USEI O CAMPO dufF PARA COLOCAR O ID DA MOVIMENTACAO CASO EXISTA
            }
            Endereco end_cep = pesquisaCep(d_cep);
            d_cidade = end_cep.getCidade() + " / " + end_cep.getUf();

            ret += "(" + idCli + "," + idDepto + ",'" + nomeDepto + "','" + sro + "','" + descricao + "','"
                    + valor + "','" + r_nome + "','" + r_cpf_cnpj + "','" + r_endereco + "','" + r_numero
                    + "','" + r_bairro + "','" + r_cidade + "','" + r_uf + "'," + "'" + d_nome + "','"
                    + d_cpf_cnpj + "','" + d_endereco + "','" + d_numero + "','" + d_bairro + "','" + d_cidade
                    + "','" + d_cep + "','" + d_uf + "','" + data + "'),";

        }
        lineNum++;
    }
    le.close();

    return ret;
}

From source file:com.fengduo.spark.commons.file.FileUtils.java

private static String getHumanReadableFileSize(long fileSize, long unit, String unitName) {
    if (fileSize == 0)
        return "0";

    if (fileSize / unit >= 1) {
        double value = fileSize / (double) unit;
        DecimalFormat df = new DecimalFormat("######.##" + unitName);
        return df.format(value);
    }/*from ww w  . j  a  va 2s. com*/
    return null;
}

From source file:com.jeans.iservlet.controller.impl.AclController.java

/**
 * ?/*w w  w .j av  a2  s  .com*/
 * 
 * @param id
 *            id
 * @return
 */
@RequestMapping(method = RequestMethod.POST, value = "/props")
@ResponseBody
public PropertyGrid loadProperties(@RequestParam long id) {
    Asset asset = astService.load(id);
    PropertyGrid props = new PropertyGrid();
    if (null != asset) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        DecimalFormat df = new DecimalFormat(",##0.00");
        props.addItem("?", null == asset.getCompany() ? null : asset.getCompany().getAlias(),
                "");
        props.addItem("", AssetConstants.getAssetTypeName(asset.getType()), "");
        props.addItem("", AssetConstants.getAssetCatalogName(asset.getCatalog()),
                "");
        props.addItem("??", asset.getName(), "");
        props.addItem("?", asset.getVendor(), "");
        props.addItem("?", asset.getModelOrVersion(), "");
        props.addItem("?", asset.getAssetUsage(), "");
        props.addItem("",
                null == asset.getPurchaseTime() ? null : sdf.format(asset.getPurchaseTime()),
                "");
        props.addItem("?", Integer.toString(asset.getQuantity()), "");
        props.addItem("", df.format(asset.getCost().doubleValue()), "");
        props.addItem("?", AssetConstants.getAssetStateName(asset.getState()), "");
        if (asset instanceof Hardware) {
            props.addItem("??", ((Hardware) asset).getSn(), "");
            props.addItem("??", ((Hardware) asset).getConfiguration(), "");
            props.addItem("??",
                    AssetConstants.getHardwareWarrantyName(((Hardware) asset).getWarranty()),
                    "");
            props.addItem("??", ((Hardware) asset).getLocation(), "");
            props.addItem("?", ((Hardware) asset).getIp(), "");
            props.addItem("??",
                    AssetConstants.getHardwareImportanceName(((Hardware) asset).getImportance()),
                    "");
            props.addItem("",
                    null == ((Hardware) asset).getOwner() ? null
                            : ((Hardware) asset).getOwner().getDepartment().getAlias() + ", "
                                    + ((Hardware) asset).getOwner().getName(),
                    "");
            props.addItem("?", ((Hardware) asset).getCode(), "");
            props.addItem("?", ((Hardware) asset).getFinancialCode(), "");
        } else if (asset instanceof Software) {
            props.addItem("",
                    AssetConstants.getSoftwareTypeName(((Software) asset).getSoftwareType()),
                    "");
            props.addItem("??", ((Software) asset).getLicense(), "");
            props.addItem("??", null == ((Software) asset).getExpiredTime() ? null
                    : sdf.format(((Software) asset).getExpiredTime()), "");
        }
        props.addItem("", asset.getComment(), "");
    }
    return props;
}

From source file:com.unicornlabs.kabouter.reporting.PowerReport.java

public static void GeneratePowerReport(Date startDate, Date endDate) {
    try {/*from w  w  w.ja  v  a2  s  .co  m*/
        Historian theHistorian = (Historian) BusinessObjectManager.getBusinessObject(Historian.class.getName());
        ArrayList<String> powerLogDeviceIds = theHistorian.getPowerLogDeviceIds();

        Document document = new Document(PageSize.A4, 50, 50, 50, 50);

        File outputFile = new File("PowerReport.pdf");
        outputFile.createNewFile();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();

        document.add(new Paragraph("Power Report for " + startDate.toString() + " to " + endDate.toString()));

        document.newPage();

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

        for (String deviceId : powerLogDeviceIds) {
            ArrayList<Powerlog> powerlogs = theHistorian.getPowerlogs(deviceId, startDate, endDate);
            double total = 0;
            double max = 0;
            Date maxTime = startDate;
            double average = 0;
            XYSeries series = new XYSeries(deviceId);
            XYDataset dataset = new XYSeriesCollection(series);

            for (Powerlog log : powerlogs) {
                total += log.getPower();
                if (log.getPower() > max) {
                    max = log.getPower();
                    maxTime = log.getId().getLogtime();
                }
                series.add(log.getId().getLogtime().getTime(), log.getPower());
            }

            average = total / powerlogs.size();

            document.add(new Paragraph("\nDevice: " + deviceId));
            document.add(new Paragraph("Average Power Usage: " + df.format(average)));
            document.add(new Paragraph("Maximum Power Usage: " + df.format(max) + " at " + maxTime.toString()));
            document.add(new Paragraph("Total Power Usage: " + df.format(total)));
            //Create a custom date axis to display dates on the X axis
            DateAxis dateAxis = new DateAxis("Date");
            //Make the labels vertical
            dateAxis.setVerticalTickLabels(true);

            //Create the power axis
            NumberAxis powerAxis = new NumberAxis("Power");

            //Set both axes to auto range for their values
            powerAxis.setAutoRange(true);
            dateAxis.setAutoRange(true);

            //Create the tooltip generator
            StandardXYToolTipGenerator ttg = new StandardXYToolTipGenerator("{0}: {2}",
                    new SimpleDateFormat("yyyy/MM/dd HH:mm"), NumberFormat.getInstance());

            //Set the renderer
            StandardXYItemRenderer renderer = new StandardXYItemRenderer(StandardXYItemRenderer.LINES, ttg,
                    null);

            //Create the plot
            XYPlot plot = new XYPlot(dataset, dateAxis, powerAxis, renderer);

            //Create the chart
            JFreeChart myChart = new JFreeChart(deviceId, JFreeChart.DEFAULT_TITLE_FONT, plot, true);

            PdfContentByte pcb = writer.getDirectContent();
            PdfTemplate tp = pcb.createTemplate(480, 360);
            Graphics2D g2d = tp.createGraphics(480, 360, new DefaultFontMapper());
            Rectangle2D r2d = new Rectangle2D.Double(0, 0, 480, 360);
            myChart.draw(g2d, r2d);
            g2d.dispose();
            pcb.addTemplate(tp, 0, 0);

            document.newPage();
        }

        document.close();

        JOptionPane.showMessageDialog(null, "Report Generated.");

        Desktop.getDesktop().open(outputFile);
    } catch (FileNotFoundException fnfe) {
        JOptionPane.showMessageDialog(null,
                "Unable To Open File For Writing, Make Sure It Is Not Currently Open");
    } catch (IOException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    } catch (DocumentException ex) {
        Logger.getLogger(PowerReport.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:graph.jfreecharts.GraphFunction.java

/**
 * A custom xyerror renderer because jfreecharts does not
 * have it supported in the api./*from  www . j a  v  a  2 s  . c om*/
 * @param title the graph title
 * @param xAxisLabel the xaxis title
 * @param yAxisLabel the yaxis title
 * @param dataset the xydataset
 * @param orientation the plot orientation
 * @param legend true to turn on legend
 * @param tooltips true to turn on tooltips (the pop up when right click)
 * @param urls // no idea what this is for
 * @return
 */
private static JFreeChart createXYIntervalChart(String title, String xAxisLabel, String yAxisLabel,
        XYDataset dataset, PlotOrientation orientation, boolean legend, boolean tooltips, boolean urls) {

    if (orientation == null) {
        throw new IllegalArgumentException("Null 'orientation' argument.");
    }
    NumberAxis xAxis = new NumberAxis(xAxisLabel);
    xAxis.setAutoRangeIncludesZero(false);
    NumberAxis yAxis = new NumberAxis(yAxisLabel);
    XYErrorRenderer renderer = new XYErrorRenderer();

    renderer.setDrawXError(true);
    renderer.setDrawYError(true);

    xAxis.setNumberFormatOverride(new DecimalFormat("0.######E0"));
    yAxis.setNumberFormatOverride(new DecimalFormat("0.######E0"));

    xAxis.setAutoRangeIncludesZero(false);
    yAxis.setAutoRangeIncludesZero(false);

    XYPlot plot = new XYPlot(dataset, xAxis, yAxis, renderer);
    plot.setOrientation(orientation);
    if (tooltips) {
        renderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
    }
    if (urls) {
        renderer.setURLGenerator(new StandardXYURLGenerator());
    }

    JFreeChart chart = new JFreeChart(title, JFreeChart.DEFAULT_TITLE_FONT, plot, legend);
    currentTheme.apply(chart);
    return chart;

}

From source file:com.prime.location.billing.InvoicedBillingManager.java

/**
 * Total Pending Billing/*ww  w .  ja  v a 2  s . c o m*/
 *
 * @return
 */
public String getTotalPending() {
    int total = 0;
    List<AgencyBilling> billings = service.findWithNamedQuery(AgencyBilling.TOTAL_PENDING_INVOICE);
    for (AgencyBilling billing : billings) {
        total += billing.getRate().intValue();
    }

    return new DecimalFormat("US$ ###,###.###").format(total);

}

From source file:org.openfaces.component.chart.impl.helpers.ChartInfoUtil.java

public static PieSectorInfo getPieSectorInfo(PieDataset pieDataset, Comparable comparable, int dsIndex) {
    double total = 0;
    List keys = pieDataset.getKeys();
    for (Object key : keys) {
        Object value = pieDataset.getValue((Comparable) key);
        if (value != null) {
            double dValue = ((Number) value).doubleValue();
            if (dValue > 0)
                total = total + dValue;/*ww  w  .java  2s  .  c  o m*/
        }
    }
    int index = pieDataset.getIndex(comparable);

    Object value = pieDataset.getValue(index);
    double dValue = 0;
    if (value != null) {
        dValue = ((Number) value).doubleValue();
    }

    PieSectorInfo sector = new PieSectorInfoImpl();
    sector.setKey(comparable);
    sector.setValue(value);
    sector.setSeriesTotal(total);
    sector.setIndex(index);
    sector.setSeries(new SeriesInfoImpl());

    sector.getSeries().setIndex(dsIndex);

    double p = (dValue / total);
    DecimalFormat nf1 = new DecimalFormat("#.00%");
    String proportionalPercent = nf1.format(p);

    sector.setProportionalValue(proportionalPercent);
    return sector;
}