Example usage for java.text NumberFormat format

List of usage examples for java.text NumberFormat format

Introduction

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

Prototype

public final String format(long number) 

Source Link

Document

Specialization of format.

Usage

From source file:com.nridge.core.base.std.StrUtl.java

/**
 * Formats the size (in bytes) in a human readable string of
 * bytes, KB, MB, GB and TB.// w w w  .  j av a  2 s . co m
 *
 * @param aSizeInBytes Size in bytes.
 *
 * @return Formatted string.
 */
public static String bytesToString(long aSizeInBytes) {
    NumberFormat numberFormat = new DecimalFormat();
    numberFormat.setMaximumFractionDigits(2);

    try {
        if (aSizeInBytes < SIZE_IN_KB)
            return numberFormat.format(aSizeInBytes) + " Byte(s)";
        else if (aSizeInBytes < SIZE_IN_MB)
            return numberFormat.format(aSizeInBytes / SIZE_IN_KB) + " KB";
        else if (aSizeInBytes < SIZE_IN_GB)
            return numberFormat.format(aSizeInBytes / SIZE_IN_MB) + " MB";
        else if (aSizeInBytes < SIZE_IN_TB)
            return numberFormat.format(aSizeInBytes / SIZE_IN_GB) + " GB";
        else
            return numberFormat.format(aSizeInBytes / SIZE_IN_TB) + " TB";
    } catch (Exception e) {
        return aSizeInBytes + " Byte(s)";
    }
}

From source file:at.alladin.rmbt.qos.testscript.TestScriptInterpreter.java

/**
 * // w  w  w. java 2s  .  co  m
 * @param args
 * @return
 * @throws ScriptException
 */
private static Object parse(String[] args, Hstore hstore, Object object, ResultOptions options)
        throws ScriptException {

    if (object == null) {
        throw new ScriptException(ScriptException.ERROR_RESULT_IS_NULL + " PARSE");
    }

    HstoreParser<?> parser = hstore.getParser(object.getClass());

    if (args.length < 1) {
        throw new ScriptException(ScriptException.ERROR_INVALID_ARGUMENT_COUNT + " PARSE: " + args.length);
    }
    if (parser == null) {
        throw new ScriptException(ScriptException.ERROR_PARSER_IS_NULL + " PARSE");
    }

    try {
        Pattern p = PATTERN_ARRAY;
        Matcher m = p.matcher(args[0]);

        if (m.find()) {
            String param = m.group(1);
            int index = Integer.valueOf(m.group(2));
            Object array = parser.getValue(param, object);

            Object indexedObject = null;
            if (array != null) {
                if (List.class.isAssignableFrom(array.getClass())) {
                    indexedObject = ((List<?>) array).get(index);
                } else if (Collection.class.isAssignableFrom(array.getClass())) {
                    Iterator<?> iterator = ((Collection<?>) array).iterator();
                    int counter = 0;
                    while (iterator.hasNext()) {
                        Object o = iterator.next();
                        if ((counter++) == index) {
                            indexedObject = o;
                            break;
                        }
                    }
                }

                if (args.length > 1) {
                    String[] nextArgs = new String[args.length - 1];
                    nextArgs = Arrays.copyOfRange(args, 1, args.length);
                    return parse(nextArgs, hstore, indexedObject, options);
                } else {
                    return indexedObject;
                }
            }
        } else {
            Object value = parser.getValue(args[0], object);
            if (args.length > 1) {
                try {
                    long divisor = Long.parseLong(args[1]);
                    int precision = 2;
                    boolean groupingUsed = false;
                    if (args.length > 2) {
                        precision = Integer.parseInt(args[2]);
                    }
                    if (args.length > 3) {
                        groupingUsed = ("t".equals(args[3].toLowerCase())
                                || "true".equals(args[3].toLowerCase()));
                    }
                    NumberFormat format = (options != null ? DecimalFormat.getInstance(options.getLocale())
                            : DecimalFormat.getInstance());
                    format.setMaximumFractionDigits(precision);
                    format.setGroupingUsed(groupingUsed);
                    format.setRoundingMode(RoundingMode.HALF_UP);
                    //System.out.println("Converting number: " + args[0] + "=" + String.valueOf(value));
                    BigDecimal number = new BigDecimal(String.valueOf(value));
                    return format.format(number.divide(new BigDecimal(divisor)));
                } catch (Exception e) {
                    //can not return parsed element
                }
            }
            //System.out.println("PARAM object: " + args[0] + " -> " + value + " of " + object.toString());
            return value;
        }
    } catch (HstoreParseException e) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + e.getMessage());
    } catch (Throwable t) {
        throw new ScriptException(ScriptException.ERROR_UNKNOWN + " PARSE: " + t.getMessage());
    }

    return null;
}

From source file:edu.cmu.tetrad.util.MatrixUtils.java

public static String toString(double[] m, NumberFormat nf) {
    StringBuilder buf = new StringBuilder();

    for (double aM : m) {
        buf.append(nf.format(aM)).append("\t");
    }//from w  ww  . j  av a 2 s  .  co  m

    return buf.toString();
}

From source file:Employee.java

public String calcMonthlySalary() {
    double monthlySalary = Salary.doubleValue() / 12;
    NumberFormat nf = NumberFormat.getCurrencyInstance();
    String str = nf.format(monthlySalary);
    return str;//from ww w  .j  a  va 2s  .c o m
}

From source file:de.perdian.commons.lang.conversion.impl.converters.NumberToStringConverter.java

@Override
protected String convertUsingFormat(NumberFormat format, Number source) {
    return source == null ? null : format.format(source);
}

From source file:com.agloco.util.StringUtil.java

private static String format(Number n, String format) {
    if (n == null)
        return "";
    NumberFormat f = new DecimalFormat(format);
    return f.format(n.doubleValue());
}

From source file:dr.PlotToolTipGenerator.java

private String generateToolTip(PCADataset dataset, int item) {

    NumberFormat formatter = new DecimalFormat("#.##");
    return "(" + formatter.format(dataset.getX(1, item)) + ", " + formatter.format(dataset.getY(1, item)) + ")";
}

From source file:de.tor.tribes.util.html.FightReportHTMLToolTipGenerator.java

public static String buildToolTip(FightReport pReport) {
    String res = pTemplateData;/* w w w . j  av  a 2  s.  c  o m*/
    String[] tables = buildUnitTables(pReport);
    SimpleDateFormat f = new SimpleDateFormat("dd.MM.yy HH:mm:ss");
    NumberFormat nf = NumberFormat.getInstance();
    nf.setMinimumFractionDigits(0);
    nf.setMaximumFractionDigits(0);
    res = res.replaceAll(WINNER_STRING,
            ((pReport.isWon() ? "Der Angreifer hat gewonnen" : "Der Verteidiger hat gewonnen")));
    res = res.replaceAll(SEND_TIME, f.format(new Date(pReport.getTimestamp())));
    res = res.replaceAll(ATTACKER_TABLE, tables[0]);
    res = res.replaceAll(DEFENDER_TABLE, tables[1]);
    res = res.replaceAll(MISC_TABLES, buildMiscTables(pReport));
    res = res.replaceAll(LUCK_STRING, "Gl&uuml;ck (aus Sicht des Angreifers)");
    res = res.replaceAll(LUCK_BAR, buildLuckBar(pReport.getLuck()));
    res = res.replaceAll(MORAL, nf.format(pReport.getMoral()) + "%");
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(1);
    res = res.replaceAll(LUCK_NEG,
            ((pReport.getLuck() < 0) ? "<b>" + nf.format(pReport.getLuck()) + "%</b>" : ""));
    res = res.replaceAll(LUCK_POS,
            ((pReport.getLuck() >= 0) ? "<b>" + nf.format(pReport.getLuck()) + "%</b>" : ""));
    res = res.replaceAll(LUCK_ICON1, "<img src=\""
            + ((pReport.getLuck() <= 0) ? FightReportHTMLToolTipGenerator.class.getResource("/res/rabe.png")
                    : FightReportHTMLToolTipGenerator.class.getResource("/res/rabe_grau.png"))
            + "\"/>");
    res = res.replaceAll(LUCK_ICON2, "<img src=\""
            + ((pReport.getLuck() >= 0) ? FightReportHTMLToolTipGenerator.class.getResource("/res/klee.png")
                    : FightReportHTMLToolTipGenerator.class.getResource("/res/klee_grau.png"))
            + "\"/>");
    res = res.replaceAll(ATTACKER, StringEscapeUtils.escapeHtml(pReport.getAttacker().getName()));
    res = res.replaceAll(SOURCE, StringEscapeUtils.escapeHtml(pReport.getSourceVillage().getFullName()));
    res = res.replaceAll(DEFENDER, StringEscapeUtils.escapeHtml(pReport.getDefender().getName()));
    res = res.replaceAll(TARGET, StringEscapeUtils.escapeHtml(pReport.getTargetVillage().getFullName()));
    res = res.replaceAll(RAM_DAMAGE,
            ((pReport.wasWallDamaged())
                    ? "Wall besch&auml;digt von Level <b>" + pReport.getWallBefore() + "</b> auf Level <b>"
                            + pReport.getWallAfter() + "</b>"
                    : ""));
    res = res.replaceAll(CATA_DAMAGE,
            ((pReport.wasBuildingDamaged()) ? pReport.getAimedBuilding() + " besch&auml;digt von Level <b>"
                    + pReport.getBuildingBefore() + "</b> auf Level <b>" + pReport.getBuildingAfter() + "</b>"
                    : ""));
    res = res.replaceAll(SNOB_INFLUENCE,
            ((pReport.wasSnobAttack())
                    ? "Zustimmung gesunken von <b>" + pReport.getAcceptanceBefore() + "</b> auf <b>"
                            + pReport.getAcceptanceAfter() + "</b>"
                    : ""));

    return res;
}

From source file:org.thymeleaf.engine21.conversion.conversion3.LongFormatter.java

public String print(final Long object, final Locale locale) {
    final NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
    return numberFormat.format(object.longValue());
}

From source file:com.liferay.portal.events.LogMemoryUsageAction.java

public void run(HttpServletRequest req, HttpServletResponse res) throws ActionException {

    Runtime runtime = Runtime.getRuntime();

    NumberFormat nf = NumberFormat.getInstance();

    String freeMemory = nf.format(runtime.freeMemory());
    String totalMemory = nf.format(runtime.totalMemory());
    String maxMemory = nf.format(runtime.maxMemory());

    _log.debug("Memory Usage:\t" + freeMemory + "\t" + totalMemory + "\t" + maxMemory);
}