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:chart.XYChart.java

private double[] formatAxis(double[] xData) {
    DecimalFormat df2 = new DecimalFormat("00.00");
    double[] formData = new double[xData.length];
    for (int i = 0; i < formData.length; i++) {

        formData[i] = new Double(df2.format(xData[i]));

    }/*from  w w w. j  a v a  2  s .  c om*/

    return formData;
}

From source file:de.uhrenbastler.watchcheck.ui.LogDialog.java

public LogDialog(Context context, Bundle logData) {
    super(context);

    setContentView(R.layout.log_dialog);
    setTitle(getContext().getString(R.string.enterLog));
    setCancelable(true);//from  ww w  .  j a  v  a 2s .c  om

    Button buttonSave = (Button) findViewById(R.id.buttonSave);
    buttonSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            makeLogEntry();
            saved = true;
            dismiss();
        }
    });

    watchId = logData.getInt(ATTR_WATCH_ID);
    deviation = logData.getDouble(ATTR_DEVIATION);
    modeNtp = logData.getBoolean(ATTR_MODE_NTP);
    localTime = (GregorianCalendar) logData.get(ATTR_LOCAL_TIME);
    ntpTime = (GregorianCalendar) logData.get(ATTR_NTP_TIME);
    lastLog = (Log) logData.get(ATTR_LAST_LOG);

    Logger.debug("watchId=" + watchId + ", deviation=" + deviation + ", modeNtp=" + modeNtp + ", localTime="
            + localTime.getTime() + ", ntpTime=" + (ntpTime != null ? ntpTime.getTime() : "NULL") + ", lastLog="
            + lastLog);

    TextView textDeviation = (TextView) findViewById(R.id.textViewDeviationValue);
    DecimalFormat df = new DecimalFormat("#.#");

    textDeviation.setText(
            (deviation > 0 ? "+" : deviation < 0 ? "-" : "+-") + df.format(Math.abs(deviation)) + " sec.");

    positionSpinner = (Spinner) findViewById(R.id.logSpinnerPosition);
    ArrayAdapter<?> positionAdapter = ArrayAdapter.createFromResource(getContext(), R.array.positions,
            android.R.layout.simple_spinner_item);
    positionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    positionSpinner.setAdapter(positionAdapter);

    if (lastLog != null && lastLog.getPosition() != null)
        positionSpinner.setSelection(ArrayUtils.indexOf(POSITIONARR, lastLog.getPosition()));
    else
        positionSpinner.setSelection(0);

    temperatureSpinner = (Spinner) findViewById(R.id.logSpinnerTemperature);
    ArrayAdapter<?> temperatureAdapter = ArrayAdapter.createFromResource(getContext(), R.array.temperatures,
            android.R.layout.simple_spinner_item);
    temperatureAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    temperatureSpinner.setAdapter(temperatureAdapter);

    if (lastLog != null)
        temperatureSpinner.setSelection(ArrayUtils.indexOf(TEMPARR, lastLog.getTemperature()));
    else
        temperatureSpinner.setSelection(0);

    comment = (EditText) findViewById(R.id.logComment);

    startFlag = (CheckBox) findViewById(R.id.logCheckBoxNewPeriod);
    startFlag.setChecked(lastLog == null);
    startFlag.setEnabled(lastLog != null);
}

From source file:org.talend.dataprofiler.chart.preview.DQRuleItemLabelGenerator.java

/**
 * DOC yyin Comment method "stringformat".
 * //from  w ww  . j a  v  a2  s . c  o  m
 * @param percent
 * @param i
 * @return
 */
private Object stringformat(Object percent, int i) {
    // ADD msjian TDQ-10793: when there is no data, the percent value is NaN
    if (Double.isNaN((double) percent)) {
        return String.valueOf(Double.NaN);
    }
    // TDQ-10793~

    BigDecimal zero = new BigDecimal(0);
    BigDecimal temp = new BigDecimal(percent.toString());
    BigDecimal min = new BigDecimal(10E-5);
    BigDecimal max = new BigDecimal(9999 * 10E-5);
    boolean isUseScientific = false;
    if (temp.compareTo(min) == -1 && temp.compareTo(zero) == 1) {
        isUseScientific = true;
    } else if (temp.compareTo(max) == 1 && temp.compareTo(new BigDecimal(1)) == -1) {
        percent = max.toString();
    }
    DecimalFormat format = (DecimalFormat) DecimalFormat.getPercentInstance(Locale.ENGLISH);
    format.applyPattern("0.00%"); //$NON-NLS-1$

    if (isUseScientific) {
        format.applyPattern("0.###E0%"); //$NON-NLS-1$
    }
    return format.format(new Double(percent.toString()));
}

From source file:de.codesourcery.flocking.ui.NumberInputField.java

protected String numberToString(Number n) {
    if (onlyIntValues) {
        return n == null ? "0" : Long.toString(n.intValue());
    }//from   w ww .  ja v a2 s  .  c  o m
    final DecimalFormat DF = new DecimalFormat("########0.0###");
    return n == null ? "0.0" : DF.format(n.doubleValue());
}

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

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

    try {// ww  w  .j ava2 s.  co m
        originalValue = Double.parseDouble(request.getParameter("originalValue"));
        conversionType = request.getParameter("conversionType");
        convertFrom = request.getParameter("convertFrom");
        convertTo = request.getParameter("convertTo");

        if (conversionType.equalsIgnoreCase("Temperature")) {
            result = convertTemp(originalValue);

            if (convertFrom.equals("1")) {
                convertFrom = "Fahrenheit";
            } else if (convertFrom.equals("2")) {
                convertFrom = "Celsius";
            } else {
                convertFrom = "Kelvin";
            }

            if (convertTo.equals("1")) {
                convertTo = "Fahrenheit";
            } else if (convertTo.equals("2")) {
                convertTo = "Celsius";
            } else {
                convertTo = "Kelvin";
            }

        }

        if (conversionType.equalsIgnoreCase("Currency")) {
            result = convertCurrency(originalValue);

            if (convertFrom.equals("1")) {
                convertFrom = "Dollars";
            } else {
                convertFrom = "Euro";
            }

            if (convertTo.equals("1")) {
                convertTo = "Dollars";
            } else {
                convertTo = "Euro";
            }

        }

        if (conversionType.equalsIgnoreCase("Volume")) {
            result = convertVolume(originalValue);

            if (convertFrom.equals("1")) {
                convertFrom = "Gallon";
            } else {
                convertFrom = "Liter";
            }

            if (convertTo.equals("1")) {
                convertTo = "Gallon";
            } else {
                convertTo = "Liter";
            }

        }

        if (conversionType.equalsIgnoreCase("Mass")) {
            result = convertMass(originalValue);

            if (convertFrom.equals("1")) {
                convertFrom = "Pound";
            } else {
                convertFrom = "Kilogram";
            }

            if (convertTo.equals("1")) {
                convertTo = "Pound";
            } else {
                convertTo = "Kilogram";
            }
        }

        DecimalFormat df = new DecimalFormat("0.00");

        model.addAttribute("result", df.format(result));
        model.addAttribute("originalValue", df.format(originalValue));
        model.addAttribute("conversionType", conversionType);
        model.addAttribute("convertFrom", convertFrom);
        model.addAttribute("convertTo", convertTo);

        //            model.addAttribute("originalAmount", df.format(originalAmount));
        //            model.addAttribute("tipAmount", df.format(tipAmount));
        //            model.addAttribute("tipPercentage", df.format(tipPercentage));
        //            model.addAttribute("finalAmount", df.format(finalAmount));
    } catch (NumberFormatException e) {
    }

    return "unitConverterResponse";
}

From source file:iphonestalker.util.FindMyIPhoneReader.java

private IPhoneLocation getLocation(JSONObject object) {
    IPhoneLocation iPhoneLocation = null;

    // Get location information
    JSONObject location = (JSONObject) object.get("location");
    if (location != null) {

        boolean locationFinished = (Boolean) location.get("locationFinished");
        if (locationFinished) {
            long timestamp = (Long) location.get("timeStamp");
            Calendar cal = Calendar.getInstance();
            cal.setTimeInMillis(timestamp);
            //System.out.println("positionType: " + location.get("positionType"));
            double horizontalAccuracy = (Double) location.get("horizontalAccuracy");
            //System.out.println("locationFinished: " + location.get("locationFinished"));
            double latitude = (Double) location.get("latitude");
            double longitude = (Double) location.get("longitude");
            //System.out.println("isOld: " + location.get("isOld"));

            DecimalFormat df = new DecimalFormat("#.0000");
            iPhoneLocation = new IPhoneLocation(Double.parseDouble(df.format(latitude)),
                    Double.parseDouble(df.format(longitude)));
            iPhoneLocation.setFulldate(cal.getTime());
            iPhoneLocation.setHorizontalAccuracy(horizontalAccuracy);
            iPhoneLocation.setConfidence(70 - (int) horizontalAccuracy);
            iPhoneLocation.setHitCount(1);
        }/*from   w  ww . ja va  2  s  . c o  m*/

    }

    return iPhoneLocation;
}

From source file:edu.cudenver.bios.matrix.test.TestOrthogonalPolynomials.java

/**
 * Write the matrix to std out/*from  w w  w .  j  a  va 2s  .c o  m*/
 * @param m
 */
private void printMatrix(String title, RealMatrix m) {
    System.out.println(title);
    DecimalFormat Number = new DecimalFormat("#0.000");
    for (int row = 0; row < m.getRowDimension(); row++) {
        for (int col = 0; col < m.getColumnDimension(); col++) {
            System.out.print(Number.format(m.getEntry(row, col)) + "\t");
        }
        System.out.print("\n");
    }
}

From source file:eu.udig.tools.jgrass.profile.ProfileView.java

public void addStopLine(double x) {

    DecimalFormat formatter = new DecimalFormat("0.0");
    // add a category marker
    ValueMarker marker = new ValueMarker(x, Color.red, new BasicStroke(1.0f));
    marker.setAlpha(0.6f);// w  w w .jav a 2s  .  c o  m
    marker.setLabel(formatter.format(x));
    marker.setLabelFont(new Font("Dialog", Font.PLAIN, 8));
    marker.setLabelTextAnchor(TextAnchor.TOP_RIGHT);
    marker.setLabelOffset(new RectangleInsets(2, 5, 2, 5));
    plot.addDomainMarker(marker, Layer.BACKGROUND);
    markers.add(marker);
}

From source file:ml.shifu.shifu.util.JexlTest.java

@Test
public void testDoubleFormat() {
    Double a = Double.NaN;
    DecimalFormat df = new DecimalFormat("##.######");

    Assert.assertEquals("NaN", a.toString());
    Assert.assertFalse(df.format(a).equals("NaN"));
}

From source file:br.com.wjaa.pagseguro.ws.PagSeguroWSImpl.java

private BigDecimal createBigDecimal(double value) {
    DecimalFormat df = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.ENGLISH);
    df.applyPattern("#,##0.00");
    String format = df.format(value);
    BigDecimal bigValue = new BigDecimal(format);

    return bigValue;

}