Example usage for java.text NumberFormat setMaximumFractionDigits

List of usage examples for java.text NumberFormat setMaximumFractionDigits

Introduction

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

Prototype

public void setMaximumFractionDigits(int newValue) 

Source Link

Document

Sets the maximum number of digits allowed in the fraction portion of a number.

Usage

From source file:ubic.gemma.analysis.expression.coexpression.links.LinkAnalysisServiceImpl.java

/**
 * Write links as text. If "known genes only", only known genes will be displayed, even if the probe in question
 * targets other "types" of genes./*from   w w w .  ja  v  a  2 s  . co m*/
 * 
 * @param la
 * @param wr
 */
private void writeLinks(final LinkAnalysis la, FilterConfig filterConfig, Writer wr) throws IOException {
    Map<CompositeSequence, Collection<Collection<Gene>>> probeToGeneMap = la.getProbeToGeneMap();
    ObjectArrayList links = la.getKeep();
    double subsetSize = la.getConfig().getSubsetSize();
    List<String> buf = new ArrayList<String>();
    if (la.getConfig().isSubset() && links.size() > subsetSize) {
        la.getConfig().setSubsetUsed(true);
    }
    wr.write(la.getConfig().toString());
    wr.write(filterConfig.toString());
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);

    Integer probeDegreeThreshold = la.getConfig().getProbeDegreeThreshold();

    Transformer officialSymbolExtractor = new Transformer() {
        @Override
        public Object transform(Object input) {
            Gene g = (Gene) input;

            return g.getOfficialSymbol();
        }
    };

    int i = 0;
    int keptLinksCount = 0;
    Random generator = new Random();
    double rand = 0.0;
    double fraction = subsetSize / links.size();
    int skippedDueToDegree = 0;
    for (int n = links.size(); i < n; i++) {

        Object val = links.getQuick(i);
        if (val == null)
            continue;
        Link m = (Link) val;
        Double w = m.getWeight();

        assert w != null;

        int x = m.getx();
        int y = m.gety();

        if (probeDegreeThreshold > 0 && (la.getProbeDegree(x) > probeDegreeThreshold
                || la.getProbeDegree(y) > probeDegreeThreshold)) {
            skippedDueToDegree++;
            continue;
        }

        CompositeSequence p1 = la.getProbe(x);
        CompositeSequence p2 = la.getProbe(y);

        Collection<Collection<Gene>> g1 = probeToGeneMap.get(p1);
        Collection<Collection<Gene>> g2 = probeToGeneMap.get(p2);

        List<String> genes1 = new ArrayList<String>();
        for (Collection<Gene> cluster : g1) {

            if (cluster.isEmpty())
                continue;

            String t = StringUtils.join(new TransformIterator(cluster.iterator(), officialSymbolExtractor),
                    ",");
            genes1.add(t);
        }

        List<String> genes2 = new ArrayList<String>();
        for (Collection<Gene> cluster : g2) {

            if (cluster.isEmpty())
                continue;

            String t = StringUtils.join(new TransformIterator(cluster.iterator(), officialSymbolExtractor),
                    ",");
            genes2.add(t);
        }

        if (genes2.size() == 0 || genes1.size() == 0) {
            continue;
        }

        String gene1String = StringUtils.join(genes1.iterator(), "|");
        String gene2String = StringUtils.join(genes2.iterator(), "|");

        if (gene1String.equals(gene2String)) {
            continue;
        }

        if (++keptLinksCount % 50000 == 0) {
            log.info(keptLinksCount + " links retained");
        }

        if (la.getConfig().isSubsetUsed()) {
            rand = generator.nextDouble();
            if (rand > fraction)
                continue;
        }

        buf.add(p1.getId() + "\t" + p2.getId() + "\t" + gene1String + "\t" + gene2String + "\t" + nf.format(w)
                + "\n");// save links
        // wr.write( p1.getId() + "\t" + p2.getId() + "\t" + gene1String + "\t" + gene2String + "\t" + nf.format( w
        // ) + "\n" );

    }

    wr.write("# totalLinks:" + keptLinksCount + "\n");
    wr.write("# printedLinks:" + buf.size() + "\n");
    wr.write("# skippedDueToHighNodeDegree:" + skippedDueToDegree + "\n");

    for (String line : buf) {// write links to file
        wr.write(line);
    }

    if (la.getConfig().isSubsetUsed()) {// subset option activated
        log.info("Done, " + keptLinksCount + "/" + links.size() + " links kept, " + buf.size()
                + " links printed");
        // wr.write("# Amount of links before subsetting/after subsetting: " + links.size() + "/" + numPrinted +
        // "\n" );
    } else {
        log.info("Done, " + keptLinksCount + "/" + links.size()
                + " links printed (some may have been filtered)");
    }
    wr.flush();

}

From source file:com.dabay6.android.apps.carlog.ui.fuel.fragments.FuelHistoryDetailFragment.java

/**
 * {@inheritDoc}/*ww w .  j a va 2s. c  om*/
 */
@SuppressWarnings("unchecked")
@Override
protected void createListItems(final Cursor cursor) {
    if (DataUtils.hasData(cursor)) {
        final Bundle bundle = getArguments();
        final FuelHistoryDTO history = FuelHistoryDTO.newInstance(cursor);
        final NumberFormat currency = NumberFormat.getCurrencyInstance();
        final String purchaseDate;

        purchaseDate = DateUtils.getUserLocaleFormattedDate(getActivity(), history.getPurchaseDate(),
                DateFormats.Medium);

        setTitle(string.fuel_history_details);
        setSubtitle(history.getName());

        if (isDualPane()) {
            adapter.clear();
        }

        adapter.add(createDetailItem(Columns.PURCHASE_DATE, purchaseDate));
        adapter.add(createDetailItem(Columns.ODOMETER_READING,
                getString(R.string.fuel_history_miles, history.getOdometerReading())));

        if (bundle != null && bundle.containsKey(PARAMS_MPG)) {
            final float mpg = bundle.getFloat(PARAMS_MPG);

            adapter.add(getString(string.fuel_history_mpg),
                    String.format(getString(string.miles_per_gallon), mpg));
        }

        currency.setMaximumFractionDigits(2);
        adapter.add(createDetailItem(Columns.TOTAL_COST, currency.format(history.getTotalCost())));

        adapter.add(createDetailItem(Columns.FUEL_AMOUNT, history.getFuelAmount().toString()));

        currency.setMaximumFractionDigits(3);
        adapter.add(createDetailItem(Columns.COST_PER_UNIT, currency.format(history.getCostPerUnit())));

        getActivity().supportInvalidateOptionsMenu();
    }
}

From source file:org.yccheok.jstock.gui.charting.InvestmentFlowLayerUI.java

private void drawTitle(Graphics2D g2) {
    final Object oldValueAntiAlias = g2.getRenderingHint(RenderingHints.KEY_ANTIALIASING);
    final Color oldColor = g2.getColor();
    final Font oldFont = g2.getFont();

    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

    final Font titleFont = oldFont.deriveFont(oldFont.getStyle() | Font.BOLD, (float) oldFont.getSize() * 1.5f);

    final int margin = 5;

    final FontMetrics titleFontMetrics = g2.getFontMetrics(titleFont);
    final FontMetrics oldFontMetrics = g2.getFontMetrics(oldFont);
    final java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance();
    numberFormat.setMaximumFractionDigits(2);
    numberFormat.setMinimumFractionDigits(2);

    final double totalInvestValue = this.investmentFlowChartJDialog.getTotalInvestValue();
    final double totalROIValue = this.investmentFlowChartJDialog.getTotalROIValue();

    final DecimalPlace decimalPlace = JStock.instance().getJStockOptions().getDecimalPlace();

    final String invest = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace,
            totalInvestValue);/* w  w w  .  j a  v a2 s . co m*/
    final String roi = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, totalROIValue);
    final double gain = totalROIValue - totalInvestValue;
    final double percentage = totalInvestValue > 0.0 ? gain / totalInvestValue * 100.0 : 0.0;
    final String gain_str = org.yccheok.jstock.portfolio.Utils.toCurrencyWithSymbol(decimalPlace, gain);
    final String percentage_str = numberFormat.format(percentage);

    final String SELECTED = this.investmentFlowChartJDialog.getCurrentSelectedString();
    final String INVEST = GUIBundle.getString("InvestmentFlowLayerUI_Invest");
    final String RETURN = GUIBundle.getString("InvestmentFlowLayerUI_Return");
    final String GAIN = (SELECTED.length() > 0 ? SELECTED + " " : "")
            + GUIBundle.getString("InvestmentFlowLayerUI_Gain");
    final String LOSS = (SELECTED.length() > 0 ? SELECTED + " " : "")
            + GUIBundle.getString("InvestmentFlowLayerUI_Loss");

    final int string_width = oldFontMetrics.stringWidth(INVEST + ": ")
            + titleFontMetrics.stringWidth(invest + " ") + oldFontMetrics.stringWidth(RETURN + ": ")
            + titleFontMetrics.stringWidth(roi + " ")
            + oldFontMetrics.stringWidth((gain >= 0 ? GAIN : LOSS) + ": ")
            + titleFontMetrics.stringWidth(gain_str + " (" + percentage_str + "%)");

    int x = (int) (this.investmentFlowChartJDialog.getChartPanel().getWidth() - string_width) >> 1;
    final int y = margin + titleFontMetrics.getAscent();

    g2.setFont(oldFont);
    g2.drawString(INVEST + ": ", x, y);
    x += oldFontMetrics.stringWidth(INVEST + ": ");
    g2.setFont(titleFont);
    g2.drawString(invest + " ", x, y);
    x += titleFontMetrics.stringWidth(invest + " ");
    g2.setFont(oldFont);
    g2.drawString(RETURN + ": ", x, y);
    x += oldFontMetrics.stringWidth(RETURN + ": ");
    g2.setFont(titleFont);
    g2.drawString(roi + " ", x, y);
    x += titleFontMetrics.stringWidth(roi + " ");
    g2.setFont(oldFont);
    if (gain >= 0) {
        if (gain > 0) {
            if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) {
                g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor());
            } else {
                g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor());
            }
        }
        g2.drawString(GAIN + ": ", x, y);
        x += oldFontMetrics.stringWidth(GAIN + ": ");
    } else {
        if (org.yccheok.jstock.engine.Utils.isFallBelowAndRiseAboveColorReverse()) {
            g2.setColor(JStock.instance().getJStockOptions().getHigherNumericalValueForegroundColor());
        } else {
            g2.setColor(JStock.instance().getJStockOptions().getLowerNumericalValueForegroundColor());
        }
        g2.drawString(LOSS + ": ", x, y);
        x += oldFontMetrics.stringWidth(LOSS + ": ");
    }
    g2.setFont(titleFont);
    g2.drawString(gain_str + " (" + percentage_str + "%)", x, y);

    g2.setColor(oldColor);
    g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, oldValueAntiAlias);
    g2.setFont(oldFont);
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.service.BugzillaXmlRpcClient.java

private String getValueStringFromObject(Object value, boolean dateWithTimezone) {
    if (value instanceof String) {
        return (String) value;
    } else if (value instanceof Boolean) {
        return (Boolean) value ? "1" : "0"; //$NON-NLS-1$ //$NON-NLS-2$
    } else if (value instanceof Integer) {
        return ((Integer) value).toString();
    } else if (value instanceof Double) {
        NumberFormat numberInstance = NumberFormat.getInstance(Locale.US);//NumberFormat.getNumberInstance();
        numberInstance.setMaximumFractionDigits(2);
        numberInstance.setMinimumFractionDigits(2);
        return numberInstance.format(value);
    } else if (value instanceof Date) {
        try {/*ww  w .j  av  a  2  s. c o  m*/
            Date y = (Date) value;
            SimpleDateFormat x0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US); //$NON-NLS-1$
            String dateString = x0.format(y);
            SimpleDateFormat x1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ZZZ"); //$NON-NLS-1$
            Date x2 = x1.parse(dateString + " GMT"); //$NON-NLS-1$
            return dateWithTimezone ? x1.format(x2) : x1.format(x2).substring(0, 10) + " 00:00:00"; //$NON-NLS-1$
        } catch (ParseException e) {
            return ""; //$NON-NLS-1$
        }
    }
    return null;
}

From source file:de.tor.tribes.ui.views.DSWorkbenchSOSRequestAnalyzer.java

private String buildSimpleRequestTable(Village pTarget, TroopAmountFixed pNeed, DefenseInformation pDefense) {
    StringBuilder b = new StringBuilder();
    SimpleDateFormat df = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
    b.append("[table]\n");
    b.append("[**]").append(pTarget.toBBCode());
    int colCount = 0;

    for (UnitHolder unit : DataHolder.getSingleton().getUnits()) {
        int value = pNeed.getAmountForUnit(unit);
        if (value > 0) {
            b.append("[|]").append("[unit]").append(unit.getPlainName()).append("[/unit]");
            colCount++;/*from   w ww  .j a  va  2 s  .com*/
        }
    }
    b.append("[/**]\n");

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    b.append("[*]");
    for (UnitHolder unit : DataHolder.getSingleton().getUnits()) {
        int value = pNeed.getAmountForUnit(unit);
        if (value > 0) {
            b.append("[|]").append(nf.format(value));
        }
    }

    b.append("[*][b]Angriffe/Fakes:[/b] ").append(pDefense.getAttackCount()).append("/")
            .append(pDefense.getFakeCount());
    for (int i = 0; i < colCount; i++) {
        b.append("[|]");
    }
    b.append("\n");
    b.append("[*][b]Zeitraum:[/b] ").append(df.format(pDefense.getFirstAttack())).append(" bis ")
            .append(df.format(pDefense.getLastAttack()));
    for (int i = 0; i < colCount; i++) {
        b.append("[|]");
    }
    b.append("\n");
    b.append("[/table]\n");

    return b.toString();
}

From source file:se.technipelago.weather.chart.Generator.java

private void createWindDial(float speed, float high, final String filename) throws IOException {
    ValueDataset dataset1 = new DefaultValueDataset(speed);
    ValueDataset dataset2 = new DefaultValueDataset(high);

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);//from   w ww  . j  a  va2  s . c o  m
    plot.setDataset(0, dataset1);
    plot.setDataset(1, dataset2);
    StandardDialFrame dialFrame = new StandardDialFrame();
    dialFrame.setBackgroundPaint(Color.lightGray);
    dialFrame.setForegroundPaint(Color.darkGray);
    plot.setDialFrame(dialFrame);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));
    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    plot.setBackground(db);

    // Wind Speed
    DialTextAnnotation annotation1 = new DialTextAnnotation("m/s");
    annotation1.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation1.setRadius(0.76);

    plot.addLayer(annotation1);

    DialValueIndicator dvi = new DialValueIndicator(0);
    dvi.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi.setOutlinePaint(Color.darkGray);
    //dvi.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt = new DecimalFormat("#");
    fmt.setMaximumFractionDigits(1);
    fmt.setMinimumIntegerDigits(1);
    dvi.setNumberFormat(fmt);
    dvi.setRadius(0.71);
    dvi.setAngle(-89.0); // -103
    dvi.setInsets(new RectangleInsets(0.0, 2.0, 0.0, 2.0)); // top, left, bottom, right
    plot.addLayer(dvi);

    StandardDialScale scale = new StandardDialScale(0, 20, -120, -300, 1, 0);
    scale.setTickRadius(0.88);
    scale.setTickLabelOffset(0.15);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    NumberFormat fmt3 = new DecimalFormat("#");
    fmt3.setMaximumFractionDigits(0);
    scale.setTickLabelFormatter(fmt3);
    plot.addScale(0, scale);

    // Add needles.
    // To make the average speed needle the front-most needle,
    // it must be added after high speed needle.
    // High speed needle.
    DialPointer needle2 = new DialPointer.Pin(1);
    needle2.setRadius(0.62);
    plot.addLayer(needle2);

    // Average speed needle.
    DialPointer needle = new DialPointer.Pointer(0);
    Color darkGreen = new Color(0x15, 0x49, 0x1f);
    ((DialPointer.Pointer) needle).setFillPaint(darkGreen);
    plot.addLayer(needle);

    // Add a cap at the dial center.
    DialCap cap = new DialCap();
    cap.setRadius(0.10);
    plot.setCap(cap);

    JFreeChart chart = new JFreeChart(plot);
    //TextTitle title = new TextTitle("Vindhastighet", new Font("Dialog", Font.BOLD, 12));
    //title.setPaint(Color.DARK_GRAY);
    //chart.setTitle(title);
    chart.setBackgroundPaint(VERY_LIGHT_GRAY);

    OutputStream out = null;
    try {
        out = new FileOutputStream(outputDir != null ? outputDir + "/" + filename : filename);
        ChartUtilities.writeChartAsPNG(out, chart, DIAL_WIDTH, DIAL_HEIGHT);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:se.technipelago.weather.chart.Generator.java

private void createTemperatureDial(float temperature, int humidity, final String filename) throws IOException {
    ValueDataset dataset1 = new DefaultValueDataset(temperature);
    ValueDataset dataset2 = new DefaultValueDataset(humidity);

    // get data for diagrams
    DialPlot plot = new DialPlot();
    plot.setView(0.0, 0.0, 1.0, 1.0);/*  ww w  .  java  2s  .co m*/
    plot.setDataset(0, dataset1);
    plot.setDataset(1, dataset2);
    StandardDialFrame dialFrame = new StandardDialFrame();
    dialFrame.setBackgroundPaint(Color.lightGray);
    dialFrame.setForegroundPaint(Color.darkGray);
    plot.setDialFrame(dialFrame);

    GradientPaint gp = new GradientPaint(new Point(), new Color(255, 255, 255), new Point(),
            new Color(170, 170, 220));
    DialBackground db = new DialBackground(gp);
    db.setGradientPaintTransformer(new StandardGradientPaintTransformer(GradientPaintTransformType.VERTICAL));
    plot.setBackground(db);

    // Temperature
    DialTextAnnotation annotation1 = new DialTextAnnotation("\u00B0C");
    annotation1.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation1.setRadius(0.76);

    plot.addLayer(annotation1);

    // Humidity
    DialTextAnnotation annotation2 = new DialTextAnnotation("%");
    annotation2.setFont(new Font("Dialog", Font.BOLD, 10));
    annotation2.setPaint(Color.blue);
    annotation2.setRadius(0.4);

    plot.addLayer(annotation2);

    // Temperature
    DialValueIndicator dvi = new DialValueIndicator(0);
    dvi.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi.setOutlinePaint(Color.darkGray);
    //dvi.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt = new DecimalFormat("#");
    fmt.setMaximumFractionDigits(1);
    fmt.setMinimumIntegerDigits(1);
    dvi.setNumberFormat(fmt);
    dvi.setRadius(0.71);
    dvi.setAngle(-88.0); // -103
    dvi.setInsets(new RectangleInsets(0.0, 8.0, 0.0, 2.0)); // top, left, bottom, right
    plot.addLayer(dvi);

    StandardDialScale scale = new StandardDialScale(-30, 30, -120, -300, 5, 4);
    scale.setTickRadius(0.88);
    scale.setTickLabelOffset(0.15);
    scale.setTickLabelFont(new Font("Dialog", Font.PLAIN, 10));
    NumberFormat fmt3 = new DecimalFormat("#");
    fmt3.setMaximumFractionDigits(0);
    scale.setTickLabelFormatter(fmt3);
    plot.addScale(0, scale);

    // Humidity
    DialValueIndicator dvi2 = new DialValueIndicator(1);
    dvi2.setFont(new Font("Dialog", Font.PLAIN, 9));
    dvi2.setOutlinePaint(Color.blue);
    //dvi2.setBackgroundPaint(new Color(0xee, 0xee, 0xf6));
    NumberFormat fmt2 = new DecimalFormat("#");
    fmt2.setMaximumFractionDigits(0);
    dvi2.setNumberFormat(fmt2);

    dvi2.setRadius(0.59);
    dvi2.setAngle(-90.0); // -77
    dvi2.setInsets(new RectangleInsets(0.0, 1.0, 0.0, 1.0));
    plot.addLayer(dvi2);

    StandardDialScale scale2 = new StandardDialScale(0, 100, -120, -300, 10, 4);
    scale2.setTickRadius(0.50);
    scale2.setTickLabelOffset(0.15);
    scale2.setTickLabelFont(new Font("Dialog", Font.PLAIN, 9));
    scale2.setTickLabelFormatter(fmt3);
    scale2.setMajorTickPaint(Color.blue);
    plot.addScale(1, scale2);
    plot.mapDatasetToScale(1, 1);

    // Add needles.
    // To make the temperature needle the front-most needle,
    // it must be added after humidity needle.
    // Humidity needle.
    DialPointer needle2 = new DialPointer.Pin(1);
    needle2.setRadius(0.50);
    plot.addLayer(needle2);

    // Temperature needle.
    DialPointer needle = new DialPointer.Pointer(0);
    Color darkGreen = new Color(0x15, 0x49, 0x1f);
    ((DialPointer.Pointer) needle).setFillPaint(darkGreen);
    plot.addLayer(needle);

    // Add a cap at the dial center.
    DialCap cap = new DialCap();
    cap.setRadius(0.10);
    plot.setCap(cap);

    JFreeChart chart = new JFreeChart(plot);
    //TextTitle title = new TextTitle("Temperatur/luftfuktighet", new Font("Dialog", Font.BOLD, 12));
    //title.setPaint(Color.DARK_GRAY);
    //chart.setTitle(title);
    chart.setBackgroundPaint(VERY_LIGHT_GRAY);

    OutputStream out = null;
    try {
        out = new FileOutputStream(outputDir != null ? outputDir + "/" + filename : filename);
        ChartUtilities.writeChartAsPNG(out, chart, DIAL_WIDTH, DIAL_HEIGHT);
    } finally {
        if (out != null) {
            out.close();
        }
    }
}

From source file:com.dabay6.android.apps.carlog.adapters.FuelHistoryCursorAdapter.java

/**
 * @param context/*  w w w. ja  v  a  2 s. com*/
 * @param view
 * @param cursor
 */
@Override
protected void populateData(final Context context, final View view, final Cursor cursor) {
    final NumberFormat currency = NumberFormat.getCurrencyInstance();
    final ViewsFinder finder = new ViewsFinder(view);
    final TextView dateTime = finder.find(R.id.datetime);
    final TextView odometer = finder.find(R.id.odometer);
    final TextView mpg = finder.find(R.id.mpg);
    final TextView price = finder.find(R.id.price);
    final TextView total = finder.find(R.id.total);
    final TextView volume = finder.find(R.id.volume);
    final FuelHistoryDTO history = FuelHistoryDTO.newInstance(cursor);
    final Pair<Float, String> calculated = calculateMilesPerGallon(context, history, cursor);

    milesPerGallon.put(history.getHistoryId(), calculated.first);

    dateTime.setText(
            DateUtils.getUserLocaleFormattedDate(context, history.getPurchaseDate(), DateFormats.Medium));
    mpg.setText(calculated.second);
    odometer.setText(
            StringUtils.format(context.getString(R.string.fuel_history_miles), history.getOdometerReading()));
    volume.setText(StringUtils.format(context.getString(R.string.gallons), history.getFuelAmount()));

    currency.setMaximumFractionDigits(3);
    price.setText(
            context.getString(R.string.fuel_history_cost_per_unit, currency.format(history.getCostPerUnit())));

    currency.setMaximumFractionDigits(2);
    total.setText(currency.format(history.getTotalCost()));
}

From source file:com.ibm.bi.dml.test.utils.TestUtils.java

/**
 * <p>/* ww w.j  av a  2 s  .co m*/
 * Returns the string representation of a double value which can be used in
 * a DML script.
 * </p>
 * 
 * @param value
 *            double value
 * @return string representation
 */
public static String getStringRepresentationForDouble(double value) {
    NumberFormat nf = DecimalFormat.getInstance(new Locale("EN"));
    nf.setGroupingUsed(false);
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(20);
    return nf.format(value);
}

From source file:org.apache.empire.struts2.jsp.controls.TextInputControl.java

protected NumberFormat getNumberFormat(DataType dataType, Locale locale, Column column) {
    if (column == null)
        return NumberFormat.getNumberInstance(locale);
    // Column is supplied
    String type = StringUtils.valueOf(column.getAttribute(InputControl.NUMBER_FORMAT_ATTRIBUTE));
    NumberFormat nf = null;
    if (type.equalsIgnoreCase("Integer"))
        nf = NumberFormat.getIntegerInstance(locale);
    /*//from  w  w w  . j  a  v  a  2s.c  o m
    else if (type.equalsIgnoreCase("Currency"))
    {   // nf = NumberFormat.getCurrencyInstance(locale);
    // Currency does not work as desired!
    nf = NumberFormat.getNumberInstance(locale);
    }
    else if (type.equalsIgnoreCase("Percent"))
    nf = NumberFormat.getPercentInstance(locale);
    */
    else
        nf = NumberFormat.getNumberInstance(locale);
    // Groups Separator?
    Object groupSep = column.getAttribute(InputControl.NUMBER_GROUPSEP_ATTRIBUTE);
    if (groupSep != null)
        nf.setGroupingUsed(ObjectUtils.getBoolean(groupSep));
    // Fraction Digits?
    Object fractDigit = column.getAttribute(InputControl.NUMBER_FRACTION_DIGITS);
    if (fractDigit != null) {
        int fractionDigits = ObjectUtils.getInteger(fractDigit);
        nf.setMaximumFractionDigits(fractionDigits);
        nf.setMinimumFractionDigits(fractionDigits);
    }
    // Number format
    return nf;
}