Example usage for java.text DecimalFormat setMinimumFractionDigits

List of usage examples for java.text DecimalFormat setMinimumFractionDigits

Introduction

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

Prototype

@Override
public void setMinimumFractionDigits(int newValue) 

Source Link

Document

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

Usage

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.EditFragment.java

/**
 * Overriden method from Fragment. Sets the appropriate TextView and ImageView
 * if the user is returning from changing the location or image. If the user is
 * returning from changing the location, the new coordinates are placed on the
 * edit_location_button Button./*from   w  w w  . java 2s. com*/
 */
@Override
public void onResume() {
    super.onResume();
    Bundle args = getArguments();
    if (EditFragment.oldText != null) {
        TextView oldTextView = (TextView) getActivity().findViewById(R.id.old_comment_text);
        oldTextView.setText(EditFragment.oldText);
    }
    if (args != null) {
        if (args.containsKey("LATITUDE") && args.containsKey("LONGITUDE")) {
            Button locButton = (Button) getActivity().findViewById(R.id.edit_location_button);
            if (args.getString("LocationType") == "CURRENT_LOCATION") {
                locButton.setText("Current Location");
            } else {
                GeoLocation geoLocation = editComment.getLocation();
                Double lat = args.getDouble("LATITUDE");
                Double lon = args.getDouble("LONGITUDE");
                geoLocation.setCoordinates(lat, lon);

                String locationDescription = args.getString("locationDescription");
                geoLocation.setLocationDescription(locationDescription);

                DecimalFormat format = new DecimalFormat();
                format.setRoundingMode(RoundingMode.HALF_EVEN);
                format.setMinimumFractionDigits(0);
                format.setMaximumFractionDigits(4);

                locButton.setText("Location: Set");
            }
        }
    }
}

From source file:org.clueminer.chameleon.GraphPropertyStore.java

public void printFancy(int w, int d) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);/*from   w w  w. j a v a 2  s . co  m*/
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);
    printFancy(new PrintWriter(System.out, true), format, w + 2);
}

From source file:org.sdr.webrec.core.WebRec.java

public void run() {

    initParameters();// ww  w. j  av  a  2  s.co  m

    String transactionName = "";
    HttpResponse response = null;

    DecimalFormat formatter = new DecimalFormat("#####0.00");
    DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);

    // make sure delimeter is a '.' instead of locale default ','
    dfs.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(dfs);

    do {
        t1 = System.currentTimeMillis();
        URL siteURL = null;
        try {

            for (int i = 0; i < url.length; i++) {

                LOGGER.debug("url:" + ((Transaction) url[i]).getUrl());

                Transaction transaction = (Transaction) url[i];
                siteURL = new URL(transaction.getUrl());
                transactionName = transaction.getName();

                //if transaction requires server authentication
                if (transaction.isAutenticate())
                    httpclient.getCredentialsProvider().setCredentials(
                            new AuthScope(siteURL.getHost(), siteURL.getPort()),
                            new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                    transaction.getWorkload().getPassword()));

                // Get HTTP GET method
                httpget = new HttpGet(((Transaction) url[i]).getUrl());

                double startTime = System.nanoTime();

                double endTime = 0.00d;

                response = null;

                // Execute HTTP GET
                try {
                    response = httpclient.execute(httpget);
                    endTime = System.nanoTime();

                } catch (Exception e) {
                    httpget.abort();
                    LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                double timeLapse = 0;

                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                        timeLapse = endTime - startTime;

                        LOGGER.debug("starttime:" + (new Double(startTime)).toString());
                        LOGGER.debug("timeLapse:" + endTime);
                        LOGGER.debug("timeLapse:" + timeLapse);

                        //move nanos to millis
                        timeLapse = timeLapse / 1000000L;
                        LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms.");
                        out.write(System.currentTimeMillis() / 1000 + ":");
                        out.write(
                                threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n");

                        //content must be consumed just because 
                        //otherwice apache httpconnectionmanager does not release connection back to pool
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            EntityUtils.toByteArray(entity);
                        }

                    } else {
                        LOGGER.error("Status code of transaction:" + transactionName + " was not "
                                + HttpURLConnection.HTTP_OK + " but "
                                + response.getStatusLine().getStatusCode());
                    }

                }
                int sleepTime = delay;
                try {
                    LOGGER.debug("Sleeping " + delay / 1000 + "s...");
                    sleep(sleepTime);
                } catch (InterruptedException ie) {
                    LOGGER.error("ERROR:" + ie);
                    ie.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage());
            e.printStackTrace();
        }
        try {
            out.flush();
            t2 = System.currentTimeMillis();
            tTask = t2 - t1;

            LOGGER.debug("Total time consumed:" + tTask / 1000 + "s.");

            if (tTask <= interval) {
                //when task takes less than preset time
                LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s.");
                sleep(interval - tTask);
            }

            cm.closeExpiredConnections();
        } catch (InterruptedException ie) {
            LOGGER.error("Error:" + ie);
            ie.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("Error:" + e);
            e.printStackTrace();
        }
    } while (true);
}

From source file:io.bitsquare.gui.util.BSFormatter.java

public String formatToPercent(double value) {
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    decimalFormat.setMinimumFractionDigits(2);
    decimalFormat.setMaximumFractionDigits(2);
    return decimalFormat.format(MathUtils.roundDouble(value * 100.0, 2)).replace(",", ".");
}

From source file:com.netease.qa.emmagee.utils.CpuInfo.java

/**
 * reserve used ratio of process CPU and total CPU, meanwhile collect
 * network traffic./* w  ww  .j  a v a 2  s . com*/
 * 
 * @return network traffic ,used ratio of process CPU and total CPU in
 *         certain interval
 */
public ArrayList<String> getCpuRatioInfo(String totalBatt, String currentBatt, String temperature,
        String voltage, String fps, boolean isRoot) {

    String heapData = "";
    DecimalFormat fomart = new DecimalFormat();
    fomart.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    fomart.setGroupingUsed(false);
    fomart.setMaximumFractionDigits(2);
    fomart.setMinimumFractionDigits(2);

    cpuUsedRatio.clear();
    idleCpu.clear();
    totalCpu.clear();
    totalCpuRatio.clear();
    readCpuStat();

    try {
        String mDateTime2;
        Calendar cal = Calendar.getInstance();
        if ((Build.MODEL.equals("sdk")) || (Build.MODEL.equals("google_sdk"))) {
            mDateTime2 = formatterFile.format(cal.getTime().getTime() + 8 * 60 * 60 * 1000);
            totalBatt = Constants.NA;
            currentBatt = Constants.NA;
            temperature = Constants.NA;
            voltage = Constants.NA;
        } else
            mDateTime2 = formatterFile.format(cal.getTime().getTime());
        if (isInitialStatics) {
            preTraffic = trafficInfo.getTrafficInfo();
            isInitialStatics = false;
        } else {
            lastestTraffic = trafficInfo.getTrafficInfo();
            if (preTraffic == -1)
                traffic = -1;
            else {
                if (lastestTraffic > preTraffic) {
                    traffic += (lastestTraffic - preTraffic + 1023) / 1024;
                }
            }
            preTraffic = lastestTraffic;
            Log.d(LOG_TAG, "lastestTraffic===" + lastestTraffic);
            Log.d(LOG_TAG, "preTraffic===" + preTraffic);
            StringBuffer totalCpuBuffer = new StringBuffer();
            if (null != totalCpu2 && totalCpu2.size() > 0) {
                processCpuRatio = fomart.format(100 * ((double) (processCpu - processCpu2)
                        / ((double) (totalCpu.get(0) - totalCpu2.get(0)))));
                for (int i = 0; i < (totalCpu.size() > totalCpu2.size() ? totalCpu2.size()
                        : totalCpu.size()); i++) {
                    String cpuRatio = "0.00";
                    if (totalCpu.get(i) - totalCpu2.get(i) > 0) {
                        cpuRatio = fomart.format(100 * ((double) ((totalCpu.get(i) - idleCpu.get(i))
                                - (totalCpu2.get(i) - idleCpu2.get(i)))
                                / (double) (totalCpu.get(i) - totalCpu2.get(i))));
                    }
                    totalCpuRatio.add(cpuRatio);
                    totalCpuBuffer.append(cpuRatio + Constants.COMMA);
                }
            } else {
                processCpuRatio = "0";
                totalCpuRatio.add("0");
                totalCpuBuffer.append("0,");
                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
            }
            // cpucsv
            for (int i = 0; i < getCpuNum() - totalCpuRatio.size() + 1; i++) {
                totalCpuBuffer.append("0.00,");
            }
            long pidMemory = mi.getPidMemorySize(pid, context);
            String pMemory = fomart.format((double) pidMemory / 1024);
            long freeMemory = mi.getFreeMemorySize(context);
            String fMemory = fomart.format((double) freeMemory / 1024);
            String percent = context.getString(R.string.stat_error);
            if (totalMemorySize != 0) {
                percent = fomart.format(((double) pidMemory / (double) totalMemorySize) * 100);
            }

            if (isPositive(processCpuRatio) && isPositive(totalCpuRatio.get(0))) {
                String trafValue;
                // whether certain device supports traffic statics or not
                if (traffic == -1) {
                    trafValue = Constants.NA;
                } else {
                    trafValue = String.valueOf(traffic);
                }
                if (isRoot) {
                    String[][] heapArray = MemoryInfo.getHeapSize(pid, context);
                    heapData = heapArray[0][1] + "/" + heapArray[0][0] + Constants.COMMA + heapArray[1][1] + "/"
                            + heapArray[1][0] + Constants.COMMA;
                }
                EmmageeService.bw.write(mDateTime2 + Constants.COMMA + ProcessInfo.getTopActivity(context)
                        + Constants.COMMA + heapData + pMemory + Constants.COMMA + percent + Constants.COMMA
                        + fMemory + Constants.COMMA + processCpuRatio + Constants.COMMA
                        + totalCpuBuffer.toString() + trafValue + Constants.COMMA + totalBatt + Constants.COMMA
                        + currentBatt + Constants.COMMA + temperature + Constants.COMMA + voltage
                        + Constants.COMMA + fps + Constants.LINE_END);

                JSONObject jsonobj = new JSONObject();
                JSONArray jsonarr = new JSONArray();
                jsonarr.put(System.currentTimeMillis());
                jsonarr.put(pMemory);
                jsonarr.put(percent);
                jsonarr.put(fMemory);
                jsonarr.put(processCpuRatio);
                jsonarr.put(totalCpuBuffer.toString().split(",")[0]);
                jsonarr.put(trafValue);
                jsonarr.put(totalBatt);
                jsonarr.put(currentBatt);
                jsonarr.put(temperature);
                jsonarr.put(voltage);
                jsonarr.put(fps);
                jsonobj.put("testSuitId", HttpUtils.testSuitId);
                jsonobj.put("data", jsonarr);

                HttpUtils.postAppPerfData(jsonobj.toString());

                totalCpu2 = (ArrayList<Long>) totalCpu.clone();
                processCpu2 = processCpu;
                idleCpu2 = (ArrayList<Long>) idleCpu.clone();
                cpuUsedRatio.add(processCpuRatio);
                cpuUsedRatio.add(totalCpuRatio.get(0));
                cpuUsedRatio.add(String.valueOf(traffic));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return cpuUsedRatio;
}

From source file:ca.ualberta.cmput301w14t08.geochan.fragments.ThreadViewFragment.java

/**
 * When comment is selected, additional information is displayed in the form
 * of location coordinates and action buttons.
 * This method sets that location field TextView in
 * the view.//ww w  .  j av a 2s. c  om
 * 
 * @param view The View of the Comment that was selected.
 * @param comment The Comment itself that was selected by the user.
 */
public void setLocationField(View view, Comment comment) {
    TextView replyLocationText = (TextView) view.findViewById(R.id.thread_view_comment_location);
    GeoLocation repLocCom = comment.getLocation();

    if (repLocCom != null) {
        if (repLocCom.getLocationDescription() != null) {
            replyLocationText.setText("near: " + repLocCom.getLocationDescription());
        } else {
            DecimalFormat format = new DecimalFormat();
            format.setRoundingMode(RoundingMode.HALF_EVEN);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(4);

            replyLocationText.setText("Latitude: " + format.format(repLocCom.getLatitude()) + " Longitude: "
                    + format.format(repLocCom.getLongitude()));
        }
    } else {
        replyLocationText.setText("Error: No location found");
    }
}

From source file:com.blackbear.flatworm.converters.CoreConverters.java

public String convertDecimal(Object obj, Map<String, ConversionOption> options) {
    Double d = (Double) obj;
    if (d == null) {
        return null;
    }/*ww w.  ja  v  a  2 s  . com*/

    int decimalPlaces = 0;
    ConversionOption conv = (ConversionOption) options.get("decimal-places");

    String decimalPlacesOption = null;
    if (null != conv)
        decimalPlacesOption = conv.getValue();

    boolean decimalImplied = "true".equals(Util.getValue(options, "decimal-implied"));

    if (decimalPlacesOption != null)
        decimalPlaces = Integer.parseInt(decimalPlacesOption);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(!decimalImplied);
    format.setGroupingUsed(false);
    if (decimalImplied) {
        format.setMaximumFractionDigits(0);
        d = new Double(d.doubleValue() * Math.pow(10D, decimalPlaces));
    } else {
        format.setMinimumFractionDigits(decimalPlaces);
        format.setMaximumFractionDigits(decimalPlaces);
    }
    return format.format(d);
}

From source file:ca.ualberta.cmput301w14t08.geochan.adapters.ThreadViewAdapter.java

/**
 * Sets the required fields of the orignal post of the thread.
 * Title, creator, comment, timestamp, location.
 * //from ww  w  . j a va 2s .  c o  m
 * @param convertView
 *            View container of a listView item.
 */
private void setOPFields(View convertView) {
    // Thread title
    TextView title = (TextView) convertView.findViewById(R.id.thread_view_op_threadTitle);
    // Special case of Viewing a Favourite Comment in ThreadView
    if (thread.getTitle().equals("")) {
        title.setVisibility(View.GONE);
        LinearLayout buttons = (LinearLayout) convertView.findViewById(R.id.thread_view_op_buttons);
        buttons.setVisibility(View.GONE);
    } else {
        title.setText(thread.getTitle());
    }
    // Thread creator
    TextView threadBy = (TextView) convertView.findViewById(R.id.thread_view_op_commentBy);
    threadBy.setText(
            "Posted by " + thread.getBodyComment().getUser() + "#" + thread.getBodyComment().getHash() + "  ");
    if (HashHelper.getHash(thread.getBodyComment().getUser()).equals(thread.getBodyComment().getHash())) {
        threadBy.setBackgroundResource(R.drawable.username_background_thread_rect);
        threadBy.setTextColor(Color.WHITE);
    }

    // Thread body comment
    TextView body = (TextView) convertView.findViewById(R.id.thread_view_op_commentBody);
    body.setText(thread.getBodyComment().getTextPost());
    // Thread timestamp
    TextView threadTime = (TextView) convertView.findViewById(R.id.thread_view_op_commentDate);
    threadTime.setText(thread.getBodyComment().getCommentDateString());
    // Location text
    TextView origPostLocationText = (TextView) convertView.findViewById(R.id.thread_view_op_locationText);
    GeoLocation loc = thread.getBodyComment().getLocation();
    String locDescriptor = loc.getLocationDescription();
    if (loc != null) {
        if (locDescriptor != null) {
            origPostLocationText.setText("near: " + locDescriptor);
        } else {
            // The rounding of long and lat for max 4 decimal digits.
            DecimalFormat format = new DecimalFormat();
            format.setRoundingMode(RoundingMode.HALF_EVEN);
            format.setMinimumFractionDigits(0);
            format.setMaximumFractionDigits(4);

            origPostLocationText.setText("Latitude: " + format.format(loc.getLatitude()) + " Longitude: "
                    + format.format(loc.getLongitude()));
        }
    }

    // Set the thumbnail if there is an image
    if (thread.getBodyComment().hasImage()) {
        ImageButton thumbnail = (ImageButton) convertView.findViewById(R.id.thread_view_comment_thumbnail);
        thumbnail.setVisibility(View.VISIBLE);
        thumbnail.setFocusable(false);
        thumbnail.setImageBitmap(thread.getBodyComment().getImageThumb());
    }
}

From source file:org.opensingular.form.wicket.mapper.MoneyMapper.java

@Override
public String getReadOnlyFormattedText(WicketBuildContext ctx, IModel<? extends SInstance> model) {
    final SInstance mi = model.getObject();

    if ((mi != null) && (mi.getValue() != null)) {

        final NumberFormat numberFormat = NumberFormat.getInstance(new Locale("pt", "BR"));
        final DecimalFormat decimalFormat = (DecimalFormat) numberFormat;
        final BigDecimal valor = (BigDecimal) mi.getValue();
        final Map<String, Object> options = withOptionsOf(model);
        final Integer digitos = (Integer) options.get(PRECISION);
        final StringBuilder pattern = new StringBuilder();

        pattern.append("R$ ###,###.");

        for (int i = 0; i < digitos; i += 1) {
            pattern.append('#');
        }/*w w w.  j  ava2 s.  c  o m*/

        decimalFormat.applyPattern(pattern.toString());
        decimalFormat.setMinimumFractionDigits(digitos);

        return decimalFormat.format(valor);
    }

    return StringUtils.EMPTY;
}

From source file:lirmm.inria.fr.math.BigSparseRealMatrix.java

@Override
public String toString() {
    DecimalFormat df;
    df = new DecimalFormat();
    df.setMaximumFractionDigits(2); //arrondi  2 chiffres apres la virgules
    df.setMinimumFractionDigits(2);
    df.setDecimalSeparatorAlwaysShown(true);
    String out = "";
    for (int i = 0; i < getRowDimension(); i++) {
        String o = "";
        for (int j = 0; j < getColumnDimension(); j++) {
            out += df.format(getEntry(i, j)).replaceAll(",", ".") + " ";
            o += df.format(getEntry(i, j)).replaceAll(",", ".") + " ";
        }//from  ww  w  .j  a  v a2  s .  com
        out += "\n";
    }
    return out;
}