Example usage for java.text DecimalFormat setMaximumFractionDigits

List of usage examples for java.text DecimalFormat setMaximumFractionDigits

Introduction

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

Prototype

@Override
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:org.mitre.math.linear.RandomMatrixExample.java

/**
 * //  ww w .  j  a  v a  2 s  . c  o m
 * @param m
 * @param width      Column width.
 * @param digits     Number of digits after the decimal.
 * @return
 */
public String matrix2String(RealMatrix m, int width, int digits) {
    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    format.setMinimumFractionDigits(digits);
    format.setGroupingUsed(false);

    StringBuilder output = new StringBuilder();
    output.append('\n'); // start on new line.
    for (int i = 0; i < m.getRowDimension(); i++) {
        for (int j = 0; j < m.getColumnDimension(); j++) {
            String s = format.format(m.getEntry(i, j)); // format the number
            int padding = Math.max(1, width - s.length()); // At _least_ 1 space
            for (int k = 0; k < padding; k++) {
                output.append(' ');
            }
            output.append(s);
        }
        output.append('\n');
    }
    output.append('\n'); // end with blank line.
    return output.toString();
}

From source file:MondrianConnector.java

public ArrayList<ArrayList<String>> ExecuteQuery2(Query queryObject) throws Exception {
    System.setProperty("mondrian.olap.SsasCompatibleNaming", "true");
    String connectionString = getConnectionString(queryObject);
    RolapConnection connection = (RolapConnection) DriverManager.getConnection(connectionString, null);
    mondrian.olap.Query query = connection.parseQuery(queryObject.getMdxQuery());
    Result result = connection.execute(query);
    ArrayList<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
    DecimalFormat df = new DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    df.setMaximumFractionDigits(340); //340 = DecimalFormat.DOUBLE_FRACTION_DIGITS
    if (result.getAxes().length == 1) {
        //Only One Axis has come so
        ArrayList<String> measures = new ArrayList<String>();
        for (Position p : result.getAxes()[0].getPositions()) {
            measures.add(p.get(0).getUniqueName().toString());
        }//  w w w . j  a v  a 2s . c o  m
        data.add(measures);

        ArrayList<String> row = new ArrayList<String>();
        for (int i = 0; i < measures.size(); i++) {

            Object value = result.getCell(new int[] { i }).getValue();
            if (value == null) {
                row.add(null);
            } else if (value instanceof Integer) {
                row.add(((Integer) value).toString());
            } else if (value instanceof Double) {
                row.add(df.format(value));
            } else {
                row.add(value.toString());
            }
        }
        data.add(row);
    } else if (result.getAxes().length == 2) {
        ArrayList<String> measures = new ArrayList<String>();
        for (Position p : result.getAxes()[0].getPositions()) {
            measures.add(p.get(0).getUniqueName().toString());
        }
        ArrayList<String> headers = new ArrayList<String>();
        ArrayList<ArrayList<DimensionItem>> dimensionItems = new ArrayList<ArrayList<DimensionItem>>();
        for (Position p : result.getAxes()[1].getPositions()) {
            ArrayList<DimensionItem> itemsAtRow = new ArrayList<DimensionItem>();
            for (Object item : p.toArray()) {
                RolapMemberBase member = (RolapMemberBase) item;
                itemsAtRow.add(new DimensionItem(member.getLevel().getHierarchy().toString(),
                        member.getCaption().toString()));
            }
            dimensionItems.add(itemsAtRow);
        }
        for (int ix = 0; ix < dimensionItems.size(); ix++) {
            ArrayList<String> row = new ArrayList<String>();
            for (DimensionItem item : dimensionItems.get(ix)) {
                if (ix == 0)
                    headers.add(item.getLevel());
                row.add(item.getCaption());
            }
            for (int i = 0; i < measures.size(); i++) {
                if (ix == 0)
                    headers.add(measures.get(i));
                Object value = result.getCell(new int[] { i, ix }).getValue();
                if (value == null) {
                    row.add("0");
                } else {
                    if (value instanceof Integer) {
                        row.add(((Integer) value).toString());
                    } else if (value instanceof Double) {
                        row.add(df.format(value));
                    } else {
                        row.add(value.toString());
                    }
                }
            }
            if (ix == 0)
                data.add(headers);
            data.add(row);
        }
    }
    return data;
}

From source file:ub.botiga.ServletDispatcher.java

private void showCistell(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession();
    User u = (User) session.getAttribute("user");
    if (u == null) {
        response.sendRedirect("/Botiga/");
        return;/*  w w  w. j  a va 2 s . c om*/
    }

    HashMap<String, Product> cistell = getCistell(request);
    HashMap<String, Product> historial = u.getProducts();
    for (Product p : historial.values()) {
        cistell.remove(p.getName());
    }
    session.setAttribute("cistell", cistell);
    if (u.getCredits() - getPreuCistell(request) < 0) {
        request.setAttribute("creditsuficient", false);
    } else {
        request.setAttribute("creditsuficient", true);
    }

    request.setAttribute("cistell", cistell.values());
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();
    dfs.setDecimalSeparator('.');

    df.setDecimalFormatSymbols(dfs);
    request.setAttribute("preucistell", df.format(getPreuCistell(request)));
    showPage(request, response, "cistell.jsp");
}

From source file:com.ning.metrics.action.hdfs.reader.HdfsEntry.java

/**
 * Pretty print the size of the file//  w  ww  .  ja  v  a  2  s  . co  m
 *
 * @return a string representing the size of the file
 */
public String getPrettySize() {
    DecimalFormat format = new DecimalFormat();
    long sizeInBytes = size;
    int i = 0;

    while (sizeInBytes > 1023 && i < SIZES.length - 1) {
        sizeInBytes /= 1024;
        i += 1;
    }

    if (sizeInBytes < 10) {
        format.setMaximumFractionDigits(1);
    }

    return format.format(sizeInBytes) + " " + SIZES[i];
}

From source file:org.arkanos.aos.api.data.Goal.java

@Override
public String toString() {
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(1);
    df.setGroupingUsed(false);//  ww  w . ja  va  2 s.c om
    String result = "{\"";
    result += Goal.FIELD_ID + "\":" + this.id + ",\"";
    result += Goal.FIELD_TITLE + "\":\"" + this.title + "\",\"";
    result += Goal.FIELD_TIME_PLANNED + "\":" + df.format(this.time_planned / 60.0f) + ",\"";
    if (this.time_planned > 0) {
        float dedication = (this.total_time_spent * 100.0f) / this.time_planned;
        result += Goal.EXTRA_DEDICATION + "\":" + df.format(dedication) + ",\"";
    }
    result += Goal.EXTRA_TOTAL_TIME_SPENT + "\":" + df.format(this.total_time_spent / 60.0f) + ",\"";
    result += Goal.EXTRA_COMPLETION + "\":" + df.format(this.completion * 100.0f) + ",\"";
    result += Goal.FIELD_DESCRIPTION + "\":\"" + this.description + "\"}";
    return result;
}

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);/*  ww w  . j  av  a2s .co  m*/
    format.setMaximumFractionDigits(d);
    format.setMinimumFractionDigits(d);
    format.setGroupingUsed(false);
    printFancy(new PrintWriter(System.out, true), format, w + 2);
}

From source file:org.openehr.rm.datatypes.quantity.DvQuantity.java

/**
 * string form displayable for humans/*from  w  w w.  j  a  v a2 s  . c  o  m*/
 *
 * @return string presentation
 */
public String toString() {
    DecimalFormat format = new DecimalFormat();
    format.setMinimumFractionDigits(precision);
    format.setMaximumFractionDigits(precision);
    DecimalFormatSymbols dfs = format.getDecimalFormatSymbols();
    dfs.setDecimalSeparator(DECIMAL_SEPARATOR);
    format.setDecimalFormatSymbols(dfs);
    format.setGroupingUsed(false);
    String tmp = format.format(magnitude) + (StringUtils.isEmpty(getUnits()) ? "" : "," + getUnits());
    return tmp;
}

From source file:com.physphil.android.unitconverterultimate.fragments.ConversionFragment.java

/**
 * Get DecimalFormat used to format result
 *
 * @return DecimalFormat/*from w w w  .jav a  2 s.  c o m*/
 */
private DecimalFormat getDecimalFormat() {
    DecimalFormat formatter = new DecimalFormat();

    //Set maximum number of decimal places
    formatter.setMaximumFractionDigits(mPrefs.getNumberDecimals());

    //Set group and decimal separators
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(mPrefs.getDecimalSeparator().charAt(0));

    String groupSeparator = mPrefs.getGroupSeparator();
    boolean isSeparatorUsed = !groupSeparator.equals(getString(R.string.group_separator_none));
    formatter.setGroupingUsed(isSeparatorUsed);
    if (isSeparatorUsed) {
        symbols.setGroupingSeparator(groupSeparator.charAt(0));
    }

    formatter.setDecimalFormatSymbols(symbols);
    return formatter;
}

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

public String convertBigDecimal(Object obj, Map<String, ConversionOption> options) {
    if (obj == null) {
        return null;
    }/* ww w.  j  a  va2 s  .  co m*/
    BigDecimal bd = (BigDecimal) obj;

    int decimalPlaces = 0;
    String decimalPlacesOption = (String) Util.getValue(options, "decimal-places");
    boolean decimalImplied = "true".equals(Util.getValue(options, "decimal-implied"));

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

    DecimalFormat format = new DecimalFormat();
    format.setDecimalSeparatorAlwaysShown(!decimalImplied);
    format.setMinimumFractionDigits(decimalPlaces);
    format.setMaximumFractionDigits(decimalPlaces);

    return format.format(bd.doubleValue());
}

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  ww.j ava  2s  .  c  o m*/
 */
@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");
            }
        }
    }
}