Example usage for java.text DecimalFormat DecimalFormat

List of usage examples for java.text DecimalFormat DecimalFormat

Introduction

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

Prototype

public DecimalFormat() 

Source Link

Document

Creates a DecimalFormat using the default pattern and symbols for the default java.util.Locale.Category#FORMAT FORMAT locale.

Usage

From source file:Main.java

public static String converSizeToString(long size) {
    String ext[] = { "B", "KB", "MB", "G", "T", "P" };
    int i = 0;/* ww w .  j  a va 2 s  .  c  o  m*/
    long duration = size;
    while (duration >= 1024) {
        System.out.println("duration=" + duration + "  i=" + i);
        duration = duration >> 10;
        i++;
        System.out.println("duration=" + duration + "  i=" + i);
    }
    double d = Math.pow(2, 10 * (i));
    java.text.DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(2);
    df.setMinimumFractionDigits(2);
    return df.format(size / d) + ext[i];
}

From source file:com.ar.dev.tierra.api.dao.impl.FiscalDAOImpl.java

@Override
public void ticket(List<DetalleFactura> detalles) {
    try (PrintWriter ticket = new PrintWriter("command/ticket.200")) {
        DecimalFormat decimalFormat = new DecimalFormat();
        decimalFormat.setMaximumFractionDigits(1);
        ticket.println("@" + (char) 28 + "T" + (char) 28 + "T");
        BigDecimal descuento = new BigDecimal(BigInteger.ZERO);
        for (DetalleFactura detalle : detalles) {
            if (detalle.getDescuentoDetalle() != null) {
                descuento = descuento.add(detalle.getDescuentoDetalle());
            }//  ww  w  . j a v a 2s  .  co m
            String price = null;
            BigDecimal sinIVA = detalle.getProducto().getPrecioVenta().subtract(detalle.getProducto()
                    .getPrecioVenta().multiply(new BigDecimal(17.35)).divide(new BigDecimal(100)));
            price = sinIVA.setScale(4, RoundingMode.HALF_UP).toString();
            ticket.println("B" + (char) 28 /*Abrimos linea*/
                    + detalle.getProducto().getDescripcion() + (char) 28 /*Nombre producto*/
                    + detalle.getCantidadDetalle() + ".0" + (char) 28 /*Cantidad*/
                    + price.replace(",", ".") + (char) 28 /*Precio unitario*/
                    + "21.0" + (char) 28 /*Impuestos IVA*/
                    + "M" + (char) 28 /*Suma monto*/
                    + "0.0" + (char) 28 /*Impuestos internos*/
                    + "0" + (char) 28 /*Parametro display*/
                    + "b");
            /*Cierra de linea*/
        }
        if (!descuento.equals(new BigDecimal(BigInteger.ZERO))) {
            ticket.println("T" + (char) 28 /*Abrimos linea descuento*/
                    + "Descuento: " + (char) 28 /*Texto a mostrar*/
                    + descuento + (char) 28 /*Monto descuento*/
                    + "m" + (char) 28 /*m: descuento, M: aumento*/
                    + "0" + (char) 28 /*parametro display*/
                    + "T");
            /*cierre linea descuento*/
        }
        ticket.println("E");
    } catch (FileNotFoundException ex) {
        Logger.getLogger(FiscalDAOImpl.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:com.streamreduce.util.MessageUtils.java

public static String roundAndTruncate(double rawValue, int precision) {
    DecimalFormat df = new DecimalFormat();

    df.setMaximumFractionDigits(precision);
    df.setMinimumFractionDigits(precision);
    df.setMinimumIntegerDigits(1);/* w  w w .  j  ava2 s. c o  m*/

    return df.format(rawValue);
}

From source file:com.redhat.rhn.common.filediff.RhnHtmlDiffWriter.java

/**
 * @param lines The number of lines in the longest file.
 *              Used to find out how many digits a line number should be.
 *              Ex: if lines is 12,  line one should be shown as 01, but
 *                  if lines is 100, line one should be shown as 001.
 *//*  w  ww .j a v  a 2  s  .c o m*/
public RhnHtmlDiffWriter(int lines) {
    onlyChanged = false;
    oldfile = new StringBuffer();
    newfile = new StringBuffer();
    formatter = new DecimalFormat();
    formatter.setMaximumFractionDigits(0);
    formatter.setMinimumIntegerDigits(Integer.toString(lines).length());
}

From source file:be.ac.ua.comp.scarletnebula.gui.BareGraph.java

/**
 * Constructor.//ww w.j  a  v  a2s .c o  m
 * 
 * @param maximumAge
 *            The age after which data is no longer displayed in the graph
 */
public BareGraph(final long maximumAge) {
    super(maximumAge);
    domain.setVisible(false);
    domain.setAutoRange(true);
    domain.setLowerMargin(0.0);
    domain.setUpperMargin(0.0);
    domain.setTickLabelsVisible(true);
    final int secondsBetweenTicks = 30;
    domain.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND, secondsBetweenTicks));

    range.setTickUnit(new NumberTickUnit(0.2, new DecimalFormat(), 5));
    range.setRange(0, 1);
    range.setVisible(false);
}

From source file:com.ancientprogramming.fixedformat4j.format.impl.AbstractDecimalFormatter.java

public String asString(T obj, FormatInstructions instructions) {
    BigDecimal roundedValue = null;
    int decimals = instructions.getFixedFormatDecimalData().getDecimals();
    if (obj != null) {
        BigDecimal value = obj instanceof BigDecimal ? (BigDecimal) obj : BigDecimal.valueOf(obj.doubleValue());

        RoundingMode roundingMode = instructions.getFixedFormatDecimalData().getRoundingMode();

        roundedValue = value.setScale(decimals, roundingMode);

        if (LOG.isDebugEnabled()) {
            LOG.debug("Value before rounding = '" + value + "', value after rounding = '" + roundedValue
                    + "', decimals = " + decimals + ", rounding mode = " + roundingMode);
        }/*w w  w .ja v a 2  s . co  m*/
    }

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalSeparatorAlwaysShown(true);
    formatter.setMaximumFractionDigits(decimals);

    char decimalSeparator = formatter.getDecimalFormatSymbols().getDecimalSeparator();
    char groupingSeparator = formatter.getDecimalFormatSymbols().getGroupingSeparator();
    String zeroString = "0" + decimalSeparator + "0";

    String rawString = roundedValue != null ? formatter.format(roundedValue) : zeroString;
    if (LOG.isDebugEnabled()) {
        LOG.debug("rawString: " + rawString + " - G[" + groupingSeparator + "] D[" + decimalSeparator + "]");
    }
    rawString = rawString.replaceAll("\\" + groupingSeparator, "");
    boolean useDecimalDelimiter = instructions.getFixedFormatDecimalData().isUseDecimalDelimiter();

    String beforeDelimiter = rawString.substring(0, rawString.indexOf(decimalSeparator));
    String afterDelimiter = rawString.substring(rawString.indexOf(decimalSeparator) + 1, rawString.length());
    if (LOG.isDebugEnabled()) {
        LOG.debug("beforeDelimiter[" + beforeDelimiter + "], afterDelimiter[" + afterDelimiter + "]");
    }

    //trim decimals
    afterDelimiter = StringUtils.substring(afterDelimiter, 0, decimals);
    afterDelimiter = StringUtils.rightPad(afterDelimiter, decimals, '0');

    String delimiter = useDecimalDelimiter ? "" + instructions.getFixedFormatDecimalData().getDecimalDelimiter()
            : "";
    String result = beforeDelimiter + delimiter + afterDelimiter;
    if (LOG.isDebugEnabled()) {
        LOG.debug("result[" + result + "]");
    }
    return result;
}

From source file:net.sourceforge.processdash.ui.web.reports.AreaChart.java

/** Create a line chart. */
public JFreeChart createChart() {
    JFreeChart chart;/*from   w w  w  .  j av a2s  . co m*/
    CategoryDataset catData = data.catDataSource();

    Object stacked = parameters.get("stacked");
    if (stacked != null) {
        chart = ChartFactory.createStackedAreaChart(null, null, null, catData, PlotOrientation.VERTICAL, true,
                true, false);
        if ("pct".equals(stacked)) {
            ((StackedAreaRenderer) chart.getCategoryPlot().getRenderer()).setRenderAsPercentages(true);
            DecimalFormat fmt = new DecimalFormat();
            fmt.setMultiplier(100);
            ((NumberAxis) chart.getCategoryPlot().getRangeAxis()).setNumberFormatOverride(fmt);
            if (parameters.get("units") == null)
                parameters.put("units", "%");
        }

    } else {
        chart = ChartFactory.createAreaChart(null, null, null, catData, PlotOrientation.VERTICAL, true, true,
                false);
    }

    setupCategoryChart(chart);

    Object colorScheme = parameters.get("colorScheme");
    if ("consistent".equals(colorScheme))
        configureConsistentColors(chart.getCategoryPlot(), catData);
    else if (parameters.containsKey("c1"))
        configureIndividualColors(chart.getCategoryPlot(), catData);

    return chart;
}

From source file:be.ac.ua.comp.scarletnebula.gui.DecoratedGraph.java

/**
 * Constructor//from ww w .ja va 2 s .co  m
 * 
 * @param maximumAge
 *            The age after which data is no longer displayed in the graph
 */
public DecoratedGraph(final long maximumAge, final Datastream stream) {
    super(maximumAge);
    this.stream = stream;
    domain.setVisible(false);
    domain.setAutoRange(true);
    domain.setLowerMargin(0.0);
    domain.setUpperMargin(0.0);
    domain.setTickLabelsVisible(true);
    domain.setTickUnit(new DateTickUnit(DateTickUnitType.SECOND, 30));

    range.setTickUnit(new NumberTickUnit(0.2, new DecimalFormat(), 5));
    range.setAutoRange(true);
    range.setVisible(true);

}

From source file:com.imagelake.android.purchasemanagement.Servlet_purchaseVisePackages.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    PrintWriter out = response.getWriter();
    try {/* w ww .  j  a va2 s. c o m*/

        String type = request.getParameter("type");

        String sql = "SELECT SQL_CALC_FOUND_ROWS user_has_packages.purchase_date,user_has_packages.expire_date,user_has_packages.user_id,user_has_packages.state,admin_package_income.total"
                + " FROM user_has_packages,admin_package_income WHERE user_has_packages.uhp_id=admin_package_income.uhp_id ";
        if (type != null && !type.equals("")) {
            if (type.equals("all")) {

                sql += "ORDER BY user_has_packages.purchase_date DESC ";
                ja = new JSONArray();
                System.out.println("sql=" + sql);
                PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    rs.close();
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();
                        DecimalFormat df = new DecimalFormat();
                        jo.put("pur_date", rs.getString(1));
                        jo.put("exp_date", rs.getString(2));
                        jo.put("un", udi.getUn(rs.getInt(3)));
                        if (rs.getInt(4) == 1) {
                            jo.put("state", 1);
                        } else if (rs.getInt(4) == 2) {
                            jo.put("state", 2);
                        }
                        jo.put("income", df.format(rs.getDouble(5)));
                        ja.add(jo);

                    }
                    System.out.println(ja.toJSONString());
                    out.write("json=" + ja.toJSONString());
                } else {
                    out.write("msg=No item found.");
                }

            } else if (type.equals("sort")) {
                ja = new JSONArray();
                String from = request.getParameter("date");
                String to = request.getParameter("date2");
                String cat = request.getParameter("cat");
                String buy = request.getParameter("buy");

                System.out.println("date_pur:" + from);
                System.out.println("date_exp:" + to);
                System.out.println("cat:" + cat);
                System.out.println("buy:" + buy);

                if (cat.equals("0")) {
                    cat = "";
                }

                if (from != null && !from.trim().equals("") && to != null && !to.trim().equals("")) {
                    String[] dt = from.split("-");
                    String[] dt2 = to.split("-");
                    String orDate = dt[2] + "-" + dt[1] + "-" + dt[0];
                    String orDate2 = dt2[2] + "-" + dt2[1] + "-" + dt2[0];
                    System.out.println("date=" + orDate);

                    sql += " AND user_has_packages.purchase_date BETWEEN '" + orDate + "' AND '" + orDate2
                            + "' ";

                }
                if (cat != null && !cat.trim().equals("")) {
                    sql += " AND user_has_packages.package_type='" + cat + "' ";
                }
                if (buy != null && !buy.trim().equals("")) {
                    sql += " AND user_has_packages.user_id='" + buy + "' ";
                }

                sql += "ORDER BY user_has_packages.purchase_date DESC ";

                System.out.println("sql: " + sql);

                PreparedStatement ps = DBFactory.getConnection().prepareStatement(sql);
                ResultSet rs = ps.executeQuery();
                DecimalFormat df = new DecimalFormat();
                if (rs.next()) {
                    rs.close();
                    rs = ps.executeQuery();
                    while (rs.next()) {
                        JSONObject jo = new JSONObject();

                        jo.put("pur_date", rs.getString(1));
                        jo.put("exp_date", rs.getString(2));
                        jo.put("un", udi.getUn(rs.getInt(3)));
                        if (rs.getInt(4) == 1) {
                            jo.put("state", 1);
                        } else if (rs.getInt(4) == 2) {
                            jo.put("state", 2);
                        }
                        jo.put("income", df.format(rs.getDouble(5)));
                        ja.add(jo);
                    }
                    System.out.println(ja.toJSONString());
                    out.write("json=" + ja.toJSONString());
                } else {
                    out.write("msg=No item found.");
                }

            }
        } else {
            out.write("msg=Internal server error,Please try again later.");
        }
    } catch (Exception e) {
        e.printStackTrace();
        out.write("msg=Internal server error,Please try again later.");
    }

}

From source file:com.aliyun.odps.ship.common.RecordConverter.java

public RecordConverter(TableSchema schema, String nullTag, String dateFormat, String tz, String charset)
        throws UnsupportedEncodingException {

    this.schema = schema;
    this.nullTag = nullTag;

    if (dateFormat == null) {
        this.dateFormatter = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT_PATTERN);
    } else {//ww  w .ja  v a 2  s. com
        dateFormatter = new SimpleDateFormat(dateFormat);
    }
    dateFormatter.setLenient(false);
    if (tz != null) {
        TimeZone t = TimeZone.getTimeZone(tz);
        if (!tz.equalsIgnoreCase("GMT") && t.getID().equals("GMT")) {
            System.err.println(
                    Constants.WARNING_INDICATOR + "possible invalid time zone: " + tz + ", fall back to GMT");
        }
        dateFormatter.setTimeZone(t);
    }

    doubleFormat = new DecimalFormat();
    doubleFormat.setMinimumFractionDigits(0);
    doubleFormat.setMaximumFractionDigits(20);

    setCharset(charset);
    r = new ArrayRecord(schema.getColumns().toArray(new Column[0]));
    nullBytes = nullTag.getBytes(defaultCharset);
}