Example usage for java.text DecimalFormat format

List of usage examples for java.text DecimalFormat format

Introduction

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

Prototype

public final String format(double number) 

Source Link

Document

Specialization of format.

Usage

From source file:net.triptech.metahive.model.SubmittedField.java

/**
 * Gets the formatted value./*w ww . jav a2s . c  o  m*/
 *
 * @return the formatted value
 */
public final String getFormattedValue() {
    String unformattedValue = "";
    String formattedValue = "";

    if (this.getDefinition() == null) {
        throw new NullPointerException("A valid definition is required");
    }

    if (StringUtils.isNotBlank(this.getValue())) {
        unformattedValue = this.getValue();
    }

    if (this.getDefinition().getDataType() == DataType.TYPE_STRING) {
        formattedValue = unformattedValue + appendUnitOfMeasure();
    }
    if (this.getDefinition().getDataType() == DataType.TYPE_BOOLEAN) {
        formattedValue = unformattedValue;
    }
    if (this.getDefinition().getDataType() == DataType.TYPE_NUMBER
            || this.getDefinition().getDataType() == DataType.TYPE_PERCENTAGE) {
        double dblValue = 0;
        try {
            dblValue = Double.parseDouble(unformattedValue);
        } catch (NumberFormatException nfe) {
            // Error parsing double
        }

        DecimalFormat df = new DecimalFormat("#.######");
        formattedValue = df.format(dblValue);
        if (StringUtils.endsWithIgnoreCase(formattedValue, ".000000")) {
            formattedValue = StringUtils.substring(formattedValue, 0, formattedValue.length() - 6);
        }

        if (this.getDefinition().getDataType() == DataType.TYPE_PERCENTAGE) {
            formattedValue += "%";
        }
        formattedValue += appendUnitOfMeasure();
    }
    if (this.getDefinition().getDataType() == DataType.TYPE_CURRENCY) {
        double dblValue = 0;
        try {
            dblValue = Double.parseDouble(unformattedValue);
        } catch (NumberFormatException nfe) {
            // Error parsing double
        }

        DecimalFormat df = new DecimalFormat("$###,###,###,##0.00");
        formattedValue = df.format(dblValue) + appendUnitOfMeasure();
    }
    return formattedValue;
}

From source file:com.pivotal.gemfire.tools.pulse.internal.service.ClusterDetailsService.java

public JSONObject execute(final HttpServletRequest request) throws Exception {

    String userName = request.getUserPrincipal().getName();

    // get cluster object
    Cluster cluster = Repository.get().getCluster();

    // json object to be sent as response
    JSONObject responseJSON = new JSONObject();

    Cluster.Alert[] alertsList = cluster.getAlertsList();
    int severeAlertCount = 0;
    int errorAlertCount = 0;
    int warningAlertCount = 0;
    int infoAlertCount = 0;

    for (Cluster.Alert alertObj : alertsList) {
        if (alertObj.getSeverity() == Cluster.Alert.SEVERE) {
            severeAlertCount++;//  w w  w.  ja va 2 s.  c  om
        } else if (alertObj.getSeverity() == Cluster.Alert.ERROR) {
            errorAlertCount++;
        } else if (alertObj.getSeverity() == Cluster.Alert.WARNING) {
            warningAlertCount++;
        } else {
            infoAlertCount++;
        }
    }
    try {
        // getting basic details of Cluster
        responseJSON.put("clusterName", cluster.getServerName());
        responseJSON.put("severeAlertCount", severeAlertCount);
        responseJSON.put("errorAlertCount", errorAlertCount);
        responseJSON.put("warningAlertCount", warningAlertCount);
        responseJSON.put("infoAlertCount", infoAlertCount);

        responseJSON.put("totalMembers", cluster.getMemberCount());
        responseJSON.put("servers", cluster.getServerCount());
        responseJSON.put("clients", cluster.getClientConnectionCount());
        responseJSON.put("locators", cluster.getLocatorCount());
        responseJSON.put("totalRegions", cluster.getTotalRegionCount());
        Long heapSize = cluster.getTotalHeapSize();

        DecimalFormat df2 = new DecimalFormat(PulseConstants.DECIMAL_FORMAT_PATTERN);
        Double heapS = heapSize.doubleValue() / 1024;
        responseJSON.put("totalHeap", Double.valueOf(df2.format(heapS)));
        responseJSON.put("functions", cluster.getRunningFunctionCount());
        responseJSON.put("uniqueCQs", cluster.getRegisteredCQCount());
        responseJSON.put("subscriptions", cluster.getSubscriptionCount());
        responseJSON.put("txnCommitted", cluster.getTxnCommittedCount());
        responseJSON.put("txnRollback", cluster.getTxnRollbackCount());
        responseJSON.put("userName", userName);
        responseJSON.put("connectedFlag", cluster.isConnectedFlag());
        responseJSON.put("connectedErrorMsg", cluster.getConnectionErrorMsg());

        return responseJSON;
    } catch (JSONException e) {
        throw new Exception(e);
    }
}

From source file:com.ecrimebureau.File.Hash.java

private byte[] createChecksum(String filename, String algo) throws Exception {
    InputStream fis = new FileInputStream(filename);
    byte[] buffer = new byte[1024];
    int percentageCompleted;
    long totalbytes = 0;

    if (isDirectory == false) {
        totalbytes = new File(filename).length();
        jProgressBar.setMaximum(100);/*from  www .ja va 2s.co m*/
    }

    MessageDigest complete = MessageDigest.getInstance(algo); //One of the following "SHA-1", "SHA-256", "SHA-384", and "SHA-512"  
    int numRead;
    long readbyte = 0;
    do {
        numRead = fis.read(buffer);

        if (numRead > 0) {
            complete.update(buffer, 0, numRead);

            if (isDirectory == false) {

                DecimalFormat df = new DecimalFormat("0.00");
                df.setRoundingMode(RoundingMode.HALF_EVEN);
                String a = df.format(((readbyte += numRead) * 100.0) / (totalbytes * 2));
                percentageCompleted = (int) Math.round(Double.parseDouble(a));
                System.out.println(readbyte += numRead);

                int pervalue = percentageCompleted;
                if (!(pervalue > 100)) {
                    jProgressBar.setValue(percentageCompleted);
                    jProgressBar.setString(String.valueOf(percentageCompleted) + "%");

                } else {

                    jProgressBar.setValue(100);
                    jProgressBar.setString(100 + "%");
                }
                //                              
            }

        }
    } while (numRead != -1);
    fis.close();
    return complete.digest();
}

From source file:com.jinhs.fetch.mirror.MirrorClientImpl.java

private void formatLocation(Location location) {
    double latitude = location.getLatitude();
    double longtitude = location.getLongitude();
    DecimalFormat df = new DecimalFormat("#.###");
    df.setRoundingMode(RoundingMode.HALF_UP);
    latitude = Double.parseDouble(df.format(latitude));
    longtitude = Double.parseDouble(df.format(longtitude));
    location.setLatitude(latitude);//from   w  w w  .j a va2  s  .c  o  m
    location.setLongitude(longtitude);
}

From source file:massbank.QueryFileUtil.java

/**
 * NG?Xg// w  ww . j  a  v  a 2 s .c om
 */
private void addList(String name, String peak) {
    DecimalFormat df = new DecimalFormat("000000");
    int no = this.nameList.size() + 1;
    if (name.equals("")) {
        name = "Compound_" + df.format(no);
    }
    this.nameList.add(name);

    String[] items = peak.split(";");
    int num = items.length;
    String[] mzs = new String[num];
    String[] intes = new String[num];
    for (int i = 0; i < items.length; i++) {
        String pair = items[i].trim();
        pair = pair.replaceAll(" +", ",");
        pair = pair.replaceAll("\t+", ",");
        String[] vals = pair.split(",");
        if (vals.length < 2 || !NumberUtils.isNumber(vals[0]) || !NumberUtils.isNumber(vals[1])) {
            mzs[i] = ("-1");
            intes[i] = ("-1");
        } else {
            mzs[i] = vals[0];
            intes[i] = vals[1];
        }

    }
    mzList.add(mzs);
    intensityList.add(intes);
}

From source file:DecimalFormatDemo.java

/** Reformats the input number and displays result. */
public void reformat() {
    try {//from   w ww .ja  v  a2s .co  m
        NumberFormat nf = NumberFormat.getNumberInstance(availableLocales.getCurrent());
        DecimalFormat df = (DecimalFormat) nf;
        df.applyPattern(currentPattern);
        result.setForeground(Color.black);
        result.setText(df.format(currentNumber));
    } catch (IllegalArgumentException iae) {
        result.setForeground(Color.red);
        result.setText("Illegal Pattern: " + iae.getMessage());
    }
}

From source file:com.ev.export.AnnualPDFExporter.java

private void addTableBody() throws Exception {
    DecimalFormat df = new DecimalFormat("#0.0");
    for (Month month : Month.values()) {
        table.addCell(new Cell(month.toString()));
        table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.GAS))));
        table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.POWER))));
        table.addCell(new Cell(df.format(consumption.getConsumption(month, Resource.WATER))));
        table.addCell(new Cell(counter.getComment(month)));
    }/*from  www.  ja v  a2  s .  c o m*/
}

From source file:estacionmeteorologica.main.java

private void jButtonincluirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonincluirActionPerformed

    DecimalFormat formatolitro = new DecimalFormat("# litros");
    String litros = formatolitro.format(Integer.valueOf(jTextFieldlitros.getText()));
    String ciudad = jTextFieldciudad.getText();
    String formatotexto = WordUtils.capitalize(ciudad);

    jTextAreatexto.append("En " + formatotexto + " - Dia: " + jSpinnerdia.getValue() + " = " + litros);

}

From source file:contactangle.ImageControl.java

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);

    if (img != null)
        g.drawImage(img, 0, 0, this);
    else//from   ww  w. ja  v  a  2  s  .c om
        g.drawString("NO IMAGE", 0, 15);

    g.setColor(Color.RED);

    if (x1 < x2 && y1 < y2)
        g.drawRect(x1, y1, x2 - x1, y2 - y1);
    else if (x1 >= x2 && y1 < y2)
        g.drawRect(x2, y1, x1 - x2, y2 - y1);
    else if (x1 < x2 && y1 >= y2)
        g.drawRect(x1, y2, x2 - x1, y1 - y2);
    else
        g.drawRect(x2, y2, x1 - x2, y1 - y2);

    if (valid && img != null) {

        if (x1 >= x2) {
            int temp = x1;
            x1 = x2;
            x2 = temp;
        }
        if (y1 >= y2) {
            int temp = y1;
            y1 = y2;
            y2 = temp;
        }

        choosenPoints = new ArrayList<Point>();
        for (int y = y1; y < y2; y++) {
            for (int x = x1; x < x2; x++) {
                int pixelData = img.getRGB(x, y);
                if (pixelData == -1)
                    choosenPoints.add(new Point(x, y));
            }
        }

        SimpleRegression reg = new SimpleRegression();
        for (Point p : choosenPoints) {
            reg.addData(p.x, p.y);
        }

        int firstX = choosenPoints.get(0).x;
        int firstY = choosenPoints.get(0).y;
        double slope = reg.getSlope();
        g.setColor(Color.GREEN);
        g.drawLine(firstX, firstY, firstX + (70), firstY + (int) (slope * (70)));
        g.drawLine(firstX, firstY, firstX - (70), firstY - (int) (slope * (70)));

        double contactDegrees = (Math.atan(reg.getSlope()) / (2 * Math.PI)) * 360.0;

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

        g.drawString("Contact Angle = ", 25, 25);
        g.drawString(d.format(contactDegrees) + " degrees", 25, 38);
    }

}

From source file:com.runwaysdk.business.generation.maven.TransferListener.java

@Override
public void transferSucceeded(TransferEvent event) {
    transferCompleted(event);//ww  w.  j a  v  a2  s .  c  o  m

    TransferResource resource = event.getResource();
    long contentLength = event.getTransferredBytes();
    if (contentLength >= 0) {
        String type = (event.getRequestType() == TransferEvent.RequestType.PUT ? "Uploaded" : "Downloaded");
        String len = contentLength >= 1024 ? toKB(contentLength) + " KB" : contentLength + " B";

        String throughput = "";
        long duration = System.currentTimeMillis() - resource.getTransferStartTime();
        if (duration > 0) {
            DecimalFormat format = new DecimalFormat("0.0", new DecimalFormatSymbols(Locale.ENGLISH));
            double kbPerSec = (contentLength / 1024.0) / (duration / 1000.0);
            throughput = " at " + format.format(kbPerSec) + " KB/sec";
        }

        log.info(type + ": " + resource.getRepositoryUrl() + resource.getResourceName() + " (" + len
                + throughput + ")");
    }
}