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:com.cypress.cysmart.BLEServiceFragments.RSCService.java

/**
 * Display live running data/*from   w  w w  .  j  av a 2 s. c  o m*/
 */
private void displayLiveData(final ArrayList<String> rsc_data) {
    if (rsc_data != null) {
        try {
            /**
             * Number formatting to two fractional decimals
             */
            Number cycledDist = NumberFormat.getInstance().parse(rsc_data.get(1));
            Number averageSpeed = NumberFormat.getInstance().parse(rsc_data.get(0));
            NumberFormat distformatter = NumberFormat.getNumberInstance();
            distformatter.setMinimumFractionDigits(2);
            distformatter.setMaximumFractionDigits(2);
            String distRan = distformatter.format(cycledDist);
            avgSpeed = distformatter.format(averageSpeed);
            mDistanceRan.setText(distRan);
            mAverageSpeed.setText(avgSpeed);
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        if (mCurrentTime == 0) {
            mGraphLastXValue = 0;
            mCurrentTime = Utils.getTimeInSeconds();
        } else {
            mPreviosTime = mCurrentTime;
            mCurrentTime = Utils.getTimeInSeconds();
            mGraphLastXValue = mGraphLastXValue + (mCurrentTime - mPreviosTime) / 1000;
        }
        try {
            float val = Float.valueOf(avgSpeed);
            mDataSeries.add(mGraphLastXValue, val);
            mChart.repaint();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

From source file:com.nextgis.mobile.fragment.AttributesFragment.java

private String parseAttributes(String data) throws RuntimeException {
    String selection = Constants.FIELD_ID + " = ?";
    Cursor attributes = mLayer.query(null, selection, new String[] { mItemId + "" }, null, null);
    if (null == attributes || attributes.getCount() == 0)
        return data;

    if (attributes.moveToFirst()) {
        for (int i = 0; i < attributes.getColumnCount(); i++) {
            String column = attributes.getColumnName(i);
            String text, alias;/*from  www.j  ava 2  s. com*/

            if (column.startsWith(Constants.FIELD_GEOM_))
                continue;

            if (column.equals(Constants.FIELD_GEOM)) {
                switch (mLayer.getGeometryType()) {
                case GTPoint:
                    try {
                        GeoPoint pt = (GeoPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.coordinates), formatCoordinates(pt));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPoint:
                    try {
                        GeoMultiPoint mpt = (GeoMultiPoint) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.center),
                                formatCoordinates(mpt.getEnvelope().getCenter()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTLineString:
                    try {
                        GeoLineString line = (GeoLineString) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), line.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiLineString:
                    try {
                        GeoMultiLineString multiline = (GeoMultiLineString) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.length),
                                LocationUtil.formatLength(getContext(), multiline.getLength(), 3));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTPolygon:
                    try {
                        GeoPolygon polygon = (GeoPolygon) GeoGeometryFactory.fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                case GTMultiPolygon:
                    try {
                        GeoMultiPolygon polygon = (GeoMultiPolygon) GeoGeometryFactory
                                .fromBlob(attributes.getBlob(i));
                        data += getRow(getString(R.string.perimeter),
                                LocationUtil.formatLength(getContext(), polygon.getPerimeter(), 3));
                        data += getRow(getString(R.string.area),
                                LocationUtil.formatArea(getContext(), polygon.getArea()));
                    } catch (IOException | ClassNotFoundException e) {
                        e.printStackTrace();
                    }
                    continue;
                default:
                    continue;
                }
            }

            Field field = mLayer.getFieldByName(column);
            int fieldType = field != null ? field.getType() : Constants.NOT_FOUND;
            switch (fieldType) {
            case GeoConstants.FTInteger:
                text = attributes.getInt(i) + "";
                break;
            case GeoConstants.FTReal:
                NumberFormat nf = NumberFormat.getInstance();
                nf.setMaximumFractionDigits(4);
                nf.setGroupingUsed(false);
                text = nf.format(attributes.getDouble(i));
                break;
            case GeoConstants.FTDate:
            case GeoConstants.FTTime:
            case GeoConstants.FTDateTime:
                text = formatDateTime(attributes.getLong(i), fieldType);
                break;
            default:
                text = toString(attributes.getString(i));
                Pattern pattern = Pattern.compile(URL_PATTERN);
                Matcher match = pattern.matcher(text);
                while (match.matches()) {
                    String url = text.substring(match.start(), match.end());
                    text = text.replaceFirst(URL_PATTERN, "<a href = '" + url + "'>" + url + "</a>");
                    match = pattern.matcher(text.substring(match.start() + url.length() * 2 + 17));
                }
                break;
            }

            if (field != null)
                alias = field.getAlias();
            else if (column.equals(Constants.FIELD_ID))
                alias = Constants.FIELD_ID;
            else
                alias = "";

            data += getRow(alias, text);
        }
    }

    attributes.close();
    return data;
}

From source file:org.totschnig.myexpenses.util.Utils.java

public static String formatCurrency(BigDecimal amount, Currency currency) {
    NumberFormat nf = getNumberFormat();
    int fractionDigits = Money.getFractionDigits(currency);
    nf.setCurrency(currency);/* www.  j  a va  2  s  .  c om*/
    if (fractionDigits <= 3) {
        nf.setMinimumFractionDigits(fractionDigits);
        nf.setMaximumFractionDigits(fractionDigits);
    } else {
        nf.setMaximumFractionDigits(fractionDigits);
    }
    return nf.format(amount);
}

From source file:com.crearo.gpslogger.ui.fragments.display.GpsSimpleViewFragment.java

public void displayLocationInfo(Location locationInfo) {
    showPreferencesSummary();/*from w  w  w .  j ava  2 s  . com*/

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);

    EditText txtLatitude = (EditText) rootView.findViewById(R.id.simple_lat_text);
    txtLatitude.setText(String.valueOf(nf.format(locationInfo.getLatitude())) + ", "
            + String.valueOf(nf.format(locationInfo.getLongitude())));

    nf.setMaximumFractionDigits(3);

    ImageView imgAccuracy = (ImageView) rootView.findViewById(R.id.simpleview_imgAccuracy);
    clearColor(imgAccuracy);

    if (locationInfo.hasAccuracy()) {

        TextView txtAccuracy = (TextView) rootView.findViewById(R.id.simpleview_txtAccuracy);
        float accuracy = locationInfo.getAccuracy();
        txtAccuracy.setText(Strings.getDistanceDisplay(getActivity(), accuracy,
                preferenceHelper.shouldDisplayImperialUnits()));

        if (accuracy > 500) {
            setColor(imgAccuracy, IconColorIndicator.Warning);
        }

        if (accuracy > 900) {
            setColor(imgAccuracy, IconColorIndicator.Bad);
        } else {
            setColor(imgAccuracy, IconColorIndicator.Good);
        }
    }

    ImageView imgAltitude = (ImageView) rootView.findViewById(R.id.simpleview_imgAltitude);
    clearColor(imgAltitude);

    if (locationInfo.hasAltitude()) {
        setColor(imgAltitude, IconColorIndicator.Good);
        TextView txtAltitude = (TextView) rootView.findViewById(R.id.simpleview_txtAltitude);

        txtAltitude.setText(Strings.getDistanceDisplay(getActivity(), locationInfo.getAltitude(),
                preferenceHelper.shouldDisplayImperialUnits()));
    }

    ImageView imgSpeed = (ImageView) rootView.findViewById(R.id.simpleview_imgSpeed);
    clearColor(imgSpeed);

    if (locationInfo.hasSpeed()) {

        setColor(imgSpeed, IconColorIndicator.Good);

        TextView txtSpeed = (TextView) rootView.findViewById(R.id.simpleview_txtSpeed);
        txtSpeed.setText(Strings.getSpeedDisplay(getActivity(), locationInfo.getSpeed(),
                preferenceHelper.shouldDisplayImperialUnits()));
    }

    ImageView imgDirection = (ImageView) rootView.findViewById(R.id.simpleview_imgDirection);
    clearColor(imgDirection);

    if (locationInfo.hasBearing()) {
        setColor(imgDirection, IconColorIndicator.Good);
        imgDirection.setRotation(locationInfo.getBearing());

        TextView txtDirection = (TextView) rootView.findViewById(R.id.simpleview_txtDirection);
        txtDirection.setText(
                String.valueOf(Math.round(locationInfo.getBearing())) + getString(R.string.degree_symbol));
    }

    TextView txtDuration = (TextView) rootView.findViewById(R.id.simpleview_txtDuration);

    long startTime = Session.getStartTimeStamp();
    long currentTime = System.currentTimeMillis();

    txtDuration.setText(Strings.getTimeDisplay(getActivity(), currentTime - startTime));

    double distanceValue = Session.getTotalTravelled();

    TextView txtPoints = (TextView) rootView.findViewById(R.id.simpleview_txtPoints);
    TextView txtTravelled = (TextView) rootView.findViewById(R.id.simpleview_txtDistance);

    txtTravelled.setText(Strings.getDistanceDisplay(getActivity(), distanceValue,
            preferenceHelper.shouldDisplayImperialUnits()));
    txtPoints.setText(Session.getNumLegs() + " " + getString(R.string.points));

    String providerName = locationInfo.getProvider();
    if (!providerName.equalsIgnoreCase(LocationManager.GPS_PROVIDER)) {
        setSatelliteCount(-1);
    }
}

From source file:ubic.gemma.core.datastructure.matrix.ExpressionDataDoubleMatrix.java

@Override
public String toString() {
    int columns = this.columns();
    int rows = this.rows();

    NumberFormat nf = NumberFormat.getInstance();
    nf.setMaximumFractionDigits(4);

    StringBuilder buf = new StringBuilder();
    if (rows <= ExpressionDataDoubleMatrix.MAX_ROWS_TO_STRING) {
        buf.append(rows).append(" x ").append(columns).append(" matrix of double values\n");
    } else {//from  ww w. j  a  va  2s  .c o m
        buf.append(rows).append(" x ").append(columns).append(" matrix of double values, showing up to ")
                .append(ExpressionDataDoubleMatrix.MAX_ROWS_TO_STRING).append(" rows\n");
    }
    int stop = 0;
    buf.append("Probe");
    for (int i = 0; i < columns; i++) {
        buf.append("\t").append(this.getBioMaterialForColumn(i).getName()).append(":");
        for (BioAssay ba : this.getBioAssaysForColumn(i)) {
            buf.append(ba.getName()).append(",");
        }
    }
    buf.append("\n");

    for (int j = 0; j < rows; j++) {

        buf.append(this.rowDesignElementMapByInteger.get(j).getName());
        for (int i = 0; i < columns; i++) {
            Double val = this.get(j, i);
            if (Double.isNaN(val)) {
                buf.append("\t").append(val);
            } else {
                buf.append("\t").append(nf.format(this.get(j, i)));
            }
        }

        buf.append("\n");

        if (stop++ > ExpressionDataDoubleMatrix.MAX_ROWS_TO_STRING) {
            buf.append("\n(Stopping after " + ExpressionDataDoubleMatrix.MAX_ROWS_TO_STRING + " rows) ...\n");
            break;
        }
    }
    return buf.toString();
}

From source file:web.diva.server.model.pca.PCAImageGenerator.java

public PCAImageGenerator(PcaResults pcaResults, DivaDataset divaDataset, int pcax, int pcay) {
    this.divaDataset = divaDataset;
    this.pcaResults = pcaResults;
    this.pcax = pcax;
    this.pcay = pcay;
    this.plot = new PcaPlot();
    plot.setMaximumSize(new Dimension(32767, 32767));
    plot.setMinimumSize(new Dimension(900, 900));
    plot.setPreferredSize(new Dimension(900, 900));
    plot.setBorder(javax.swing.BorderFactory.createLineBorder(Color.BLUE));
    plot.setLayout(new java.awt.FlowLayout(0, 5, 1));
    plot.setSize(900, 900);/*from  w  ww.  jav a  2  s  .  c  o  m*/
    plot.setBackground(Color.WHITE);
    indexToZoomed = new int[divaDataset.getDataLength()];//        
    updatePlot();
    pcaLabelData = new String[pcaResults.eigenvalues.length];
    for (int i = 0; i < pcaResults.eigenvalues.length; i++) {
        pcaLabelData[i] = ("Principal Component nr." + String.valueOf(i + 1) + " - "
                + pcaResults.varianceastr(i) + "% var.");
    }
    double totalvar = 0.0;
    java.text.NumberFormat numformat = java.text.NumberFormat.getNumberInstance(java.util.Locale.US);
    numformat.setMaximumFractionDigits(1);
    if (pcax != pcay) {
        totalvar = pcaResults.varianceaccounted(pcax) + pcaResults.varianceaccounted(pcay);
    } else {
        totalvar = pcaResults.varianceaccounted(pcax);
    }
    totalvarStr = ("Total variance retained: " + numformat.format(totalvar) + "% var.");

}

From source file:de.xwic.appkit.webbase.table.DefaultColumnLabelProvider.java

private String toString(Object value) {
    String text;//from   w  w  w  .  j  ava 2 s  .  co  m

    if (value == null) {
        text = "";
    } else if (value instanceof Date) {
        // special treatment for date objects
        text = dateFormatter.format((Date) value);
    } else if (value instanceof Calendar) {
        Calendar c = (Calendar) value;
        text = dateFormatter.format(c.getTime());
    } else if (value instanceof Long) {
        NumberFormat nf = NumberFormat.getNumberInstance(locale);
        text = nf.format(((Long) value).longValue());
    } else if (value instanceof Double) {
        NumberFormat nf = NumberFormat.getNumberInstance(locale);
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(2);
        text = nf.format(((Double) value).doubleValue());
    } else if (propertyEditor != null) {
        propertyEditor.setValue(value);
        text = propertyEditor.getAsText();
    } else if (value instanceof IPicklistEntry) {
        text = ((IPicklistEntry) value).getBezeichnung(locale.getLanguage());
    } else if (value instanceof IEntity) {
        IEntity entity = (IEntity) value;
        DAO<?> dao = DAOSystem.findDAOforEntity(entity.type());
        text = dao.buildTitle(entity);
    } else if (value instanceof Collection<?>) {
        // set of picklist entries
        StringBuffer sb = new StringBuffer();
        for (Iterator<?> it = ((Collection<?>) value).iterator(); it.hasNext();) {
            Object o = it.next();
            if (sb.length() != 0) {
                sb.append(",");
            }
            sb.append(toString(o));
        }
        text = sb.toString();
    } else if (value instanceof Object[]) {
        StringBuffer sb = new StringBuffer();
        Object[] values = (Object[]) value;
        for (int i = 0; i < values.length; i++) {
            if (sb.length() != 0) {
                sb.append(",");
            }
            sb.append(toString(values[i]));
        }
        text = sb.toString();
    } else {
        text = value.toString();
    }
    return text;

}

From source file:org.moqui.impl.context.L10nFacadeImpl.java

@Override
public String formatCurrency(Object amount, String uomId, Integer fractionDigits, Locale locale) {
    if (amount == null)
        return "";
    if (amount instanceof CharSequence) {
        if (((CharSequence) amount).length() == 0) {
            return "";
        } else {//from w w w.j ava  2  s . c o  m
            amount = parseNumber((String) amount, null);
        }
    }

    if (locale == null)
        locale = getLocale();
    NumberFormat nf = NumberFormat.getCurrencyInstance(locale);
    Currency currency = uomId != null && uomId.length() > 0 ? Currency.getInstance(uomId) : null;
    if (currency != null)
        nf.setCurrency(currency);
    if (fractionDigits == null)
        fractionDigits = currency != null ? currency.getDefaultFractionDigits() : 2;
    nf.setMaximumFractionDigits(fractionDigits);
    nf.setMinimumFractionDigits(fractionDigits);
    return nf.format(amount);
}

From source file:mx.edu.um.mateo.inventario.dao.impl.FacturaAlmacenDaoHibernate.java

private String getFolio(Almacen almacen) {
    Query query = currentSession()
            .createQuery("select f from Folio f where f.nombre = :nombre and f.almacen.id = :almacenId");
    query.setString("nombre", "FACTURA");
    query.setLong("almacenId", almacen.getId());
    query.setLockOptions(LockOptions.UPGRADE);
    Folio folio = (Folio) query.uniqueResult();
    if (folio == null) {
        folio = new Folio("FACTURA");
        folio.setAlmacen(almacen);//from ww  w.j  av  a  2 s.c  o  m
        currentSession().save(folio);
        return getFolio(almacen);
    }
    folio.setValor(folio.getValor() + 1);
    java.text.NumberFormat nf = java.text.DecimalFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumIntegerDigits(9);
    nf.setMaximumIntegerDigits(9);
    nf.setMaximumFractionDigits(0);
    StringBuilder sb = new StringBuilder();
    sb.append("FA-");
    sb.append(almacen.getEmpresa().getOrganizacion().getCodigo());
    sb.append(almacen.getEmpresa().getCodigo());
    sb.append(almacen.getCodigo());
    sb.append(nf.format(folio.getValor()));
    return sb.toString();
}

From source file:mx.edu.um.mateo.inventario.dao.impl.FacturaAlmacenDaoHibernate.java

private String getFolioTemporal(Almacen almacen) {
    Query query = currentSession()
            .createQuery("select f from Folio f where f.nombre = :nombre and f.almacen.id = :almacenId");
    query.setString("nombre", "FACTURA-TEMPORAL");
    query.setLong("almacenId", almacen.getId());
    query.setLockOptions(LockOptions.UPGRADE);
    Folio folio = (Folio) query.uniqueResult();
    if (folio == null) {
        folio = new Folio("FACTURA-TEMPORAL");
        folio.setAlmacen(almacen);//from www  . j  a v  a 2  s  .c o m
        currentSession().save(folio);
        currentSession().flush();
        return getFolioTemporal(almacen);
    }
    folio.setValor(folio.getValor() + 1);
    java.text.NumberFormat nf = java.text.DecimalFormat.getInstance();
    nf.setGroupingUsed(false);
    nf.setMinimumIntegerDigits(9);
    nf.setMaximumIntegerDigits(9);
    nf.setMaximumFractionDigits(0);
    StringBuilder sb = new StringBuilder();
    sb.append("TF-");
    sb.append(almacen.getEmpresa().getOrganizacion().getCodigo());
    sb.append(almacen.getEmpresa().getCodigo());
    sb.append(almacen.getCodigo());
    sb.append(nf.format(folio.getValor()));
    return sb.toString();
}