Example usage for java.text DecimalFormat format

List of usage examples for java.text DecimalFormat format

Introduction

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

Prototype

public final String format(double number) 

Source Link

Document

Specialization of format.

Usage

From source file:io.hops.hopsworks.common.util.HopsUtils.java

/**
 * Converts HDFS quota from Bytes to a human friendly format
 * @param quota/*from ww  w.  j a v a  2s. com*/
 * @return
 */
public static String spaceQuotaToString(long quota) {
    DecimalFormat df = new DecimalFormat("##.##");

    if (quota > 1099511627776L) {
        float tbSize = quota / 1099511627776L;
        return df.format(tbSize) + "TB";
    } else if (quota > 1073741824L) {
        float gbSize = quota / 1073741824L;
        return df.format(gbSize) + "GB";
    } else if (quota >= 0) {
        float mbSize = quota / 1048576;
        return df.format(mbSize) + "MB";
    } else {
        return "-1MB";
    }
}

From source file:edu.psu.iam.cpr.core.util.Utility.java

/**
 * Format a 'int' number with default pattern
 *
 * @param number/*from   ww w .  ja va2  s.  co m*/
 * @return contains the string representation.
 */
public static String formatInt(final int number) {
    String result = null;
    DecimalFormat df = new DecimalFormat(INTEGER_PATTERN);

    try {
        result = df.format(number);
    } catch (ArithmeticException ae) {
    }

    return result;
}

From source file:edu.psu.iam.cpr.core.util.Utility.java

/**
 * Format a 'long' number with default pattern
 *
 * @param number//from  w  ww.  j  a  va2 s .c  om
 * @return contains the string representation.
 */
public static String formatLong(final long number) {
    String result = null;
    DecimalFormat df = new DecimalFormat(INTEGER_PATTERN);

    try {
        result = df.format(number);
    } catch (ArithmeticException ae) {
    }

    return result;
}

From source file:de.julielab.jtbd.TokenizerApplication.java

/**
 * perform cross validation//from  w w w  . j a  v  a  2 s  .c  o m
 *
 * @param n
 *            number of splits
 * @param orgSentencesFile
 * @param tokSentencesFile
 * @param errors
 * @param predictions
 * @return
 */
private static double doCrossEvaluation(final int n, final File orgSentencesFile, final File tokSentencesFile,
        final ArrayList<String> errors, final ArrayList<String> predictions) {

    final ArrayList<String> orgSentences = readFile(orgSentencesFile);
    final ArrayList<String> tokSentences = readFile(tokSentencesFile);

    final long seed = 1;
    Collections.shuffle(orgSentences, new Random(seed));
    Collections.shuffle(tokSentences, new Random(seed));

    int pos = 0;
    final int sizeRound = orgSentences.size() / n;
    final int sizeAll = orgSentences.size();
    final int sizeLastRound = sizeRound + (sizeAll % n);
    System.out.println("number of files in directory: " + sizeAll);
    System.out.println("size of each/last round: " + sizeRound + "/" + sizeLastRound);
    System.out.println();

    final EvalResult[] er = new EvalResult[n]; //
    double avgAcc = 0;
    double avgF = 0;

    for (int i = 0; i < n; i++) { // in each round

        final ArrayList<String> predictOrgSentences = new ArrayList<String>();
        final ArrayList<String> predictTokSentences = new ArrayList<String>();
        final ArrayList<String> trainOrgSentences = new ArrayList<String>();
        final ArrayList<String> trainTokSentences = new ArrayList<String>();

        if (i == (n - 1)) {
            // last round
            for (int j = 0; j < orgSentences.size(); j++)
                if (j < pos) {
                    trainOrgSentences.add(orgSentences.get(j));
                    trainTokSentences.add(tokSentences.get(j));
                } else {
                    predictOrgSentences.add(orgSentences.get(j));
                    predictTokSentences.add(tokSentences.get(j));
                }

        } else {
            // other rounds
            for (int j = 0; j < orgSentences.size(); j++)
                if ((j < pos) || (j >= (pos + sizeRound))) {
                    // System.out.println(j + " - add to train");
                    trainOrgSentences.add(orgSentences.get(j));
                    trainTokSentences.add(tokSentences.get(j));
                } else {
                    predictOrgSentences.add(orgSentences.get(j));
                    predictTokSentences.add(tokSentences.get(j));
                }
            pos += sizeRound;
        }

        // now evaluate for this round
        System.out.println("training size: " + trainOrgSentences.size());
        System.out.println("prediction size: " + predictOrgSentences.size());
        er[i] = doEvaluation(trainOrgSentences, trainTokSentences, predictOrgSentences, predictTokSentences,
                predictions, errors);
    }

    final DecimalFormat df = new DecimalFormat("0.000");
    for (int i = 0; i < er.length; i++) {
        avgAcc += er[i].ACC;
        avgF += er[i].getF();
        System.out.println("ACC in round " + i + ": " + df.format(er[i].ACC));
    }
    avgAcc = avgAcc / n;
    avgF = avgF / n;

    System.out.println("\n\n------------------------------------");
    System.out.println("avg accuracy: " + df.format(avgAcc));
    System.out.println("avg F-score: " + df.format(avgF));
    System.out.println("------------------------------------");
    return avgAcc;

}

From source file:com.addthis.hydra.task.output.tree.TreeMapper.java

/**
 * number right pad utility for log data
 *//*  ww  w.j a v a2s.  c om*/
private static String pad(long v, int chars) {
    String sv = Long.toString(v);
    String[] opt = new String[] { "K", "M", "B", "T" };
    DecimalFormat[] dco = new DecimalFormat[] { new DecimalFormat("0.00"), new DecimalFormat("0.0"),
            new DecimalFormat("0") };
    int indx = 0;
    double div = 1000d;
    outer: while (sv.length() > chars - 1 && indx < opt.length) {
        for (DecimalFormat dc : dco) {
            sv = dc.format(v / div).concat(opt[indx]);
            if (sv.length() <= chars - 1) {
                break outer;
            }
        }
        div *= 1000;
        indx++;
    }
    return Strings.padright(sv, chars);
}

From source file:com.krawler.common.util.BaseStringUtil.java

public static String convertToTwoDecimal(double value) {
    java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");
    return df.format(value);
}

From source file:com.opengamma.bbg.util.BloombergDataUtils.java

/**
 * Generates an equity option ticker from details about the option.
 * /*from   w w w .  j a v a 2 s.  c o m*/
 * @param underlyingTicker the ticker of the underlying equity, not null
 * @param expiry the option expiry, not null
 * @param optionType the option type, not null
 * @param strike the strike rate
 * @return the equity option ticker, not null
 */
public static ExternalId generateEquityOptionTicker(final String underlyingTicker, final Expiry expiry,
        final OptionType optionType, final double strike) {
    ArgumentChecker.notNull(underlyingTicker, "underlyingTicker");
    ArgumentChecker.notNull(expiry, "expiry");
    ArgumentChecker.notNull(optionType, "optionType");
    Pair<String, String> tickerMarketSectorPair = splitTickerAtMarketSector(underlyingTicker);
    DateTimeFormatter expiryFormatter = DateTimeFormatter.ofPattern("MM/dd/yy");
    DecimalFormat strikeFormat = new DecimalFormat("0.###");
    String strikeString = strikeFormat.format(strike);
    StringBuilder sb = new StringBuilder();
    sb.append(tickerMarketSectorPair.getFirst()).append(' ')
            .append(expiry.getExpiry().toString(expiryFormatter)).append(' ')
            .append(optionType == OptionType.PUT ? 'P' : 'C').append(strikeString).append(' ')
            .append(tickerMarketSectorPair.getSecond());
    return ExternalId.of(ExternalSchemes.BLOOMBERG_TICKER, sb.toString());
}

From source file:com.att.aro.core.util.Util.java

/**
 * Formats a number so that the number of digits in the fraction
 * portion of it is bound by a maximum value and a minimum value.
 * <br>//from   ww  w .j av  a2s  .  c o  m
 * <br>
 * Examples with maxFractionDigits being 3 and
 * minFractionDigits being 0:
 * <br>2.4535 -> 2.454
 * <br>20 -> 20
 * <br>24535 -> 24535
 * <br>2.5 -> 2.5
 * <br>2.460 -> 2.46
 * <br>2.40 -> 2.4
 * <br>3.12 -> 3.12
 * <br>9.888 -> 9.888
 *
 * @param number
 * @param maxFractionDigits maximum number of fraction digits,
 * replaced by 0 if it is a negative value
 * @param minFractionDigits minimum number of fraction digits,
 * replaced by 0 if it is a negative value
 * @return
 */
public static String formatDecimal(BigDecimal number, int maxFractionDigits, int minFractionDigits) {
    DecimalFormat df = new DecimalFormat();
    df.setGroupingUsed(false);
    df.setMaximumFractionDigits(maxFractionDigits);
    df.setMinimumFractionDigits(minFractionDigits);
    return df.format(number);
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a double value at the field./* ww w . j  ava 2  s . c  o  m*/
 * 
 * @param value
 *            the value
 * @param formatMask
 *            the decorator mask
 * @param transformMask
 *            the transformation mask
 * @return false if problem otherwise true
 */
protected static String toDouble(final Double value, final String formatMask, final String transformMask) {
    if (value != null) {
        if (StringUtils.isNotBlank(transformMask)) {
            // apply transformation mask
            DecimalFormat df = new DecimalFormat(transformMask);
            return df.format((Double) value).replace(Constants.COMMA, Constants.DOT);

        } else if (StringUtils.isNotBlank(formatMask)) {
            // apply format mask
            DecimalFormat df = new DecimalFormat(formatMask);
            return df.format((Double) value).replace(Constants.COMMA, Constants.DOT);

        } else {
            return value.toString().replace(Constants.COMMA, Constants.DOT); // the
            // exact
            // value
        }
    }
    return StringUtils.EMPTY; // empty field
}

From source file:net.ceos.project.poi.annotated.core.CsvHandler.java

/**
 * Apply a big decimal value at the field.
 * /*from  w  w w .j a  v a 2s .c o m*/
 * @param value
 *            the value
 * @param formatMask
 *            the decorator mask
 * @param transformMask
 *            the transformation mask
 * @return false if problem otherwise true
 */
protected static String toBigDecimal(final BigDecimal value, final String formatMask,
        final String transformMask) {
    if (value != null) {
        Double dBigDecimal = value.doubleValue();
        if (StringUtils.isNotBlank(transformMask)) {
            // apply transformation mask
            DecimalFormat df = new DecimalFormat(transformMask);
            return df.format(dBigDecimal);

        } else if (StringUtils.isNotBlank(formatMask)) {
            // apply format mask
            DecimalFormat df = new DecimalFormat(formatMask);
            return df.format(dBigDecimal);

        } else {
            return value.toString(); // the exact value
        }
    }
    return StringUtils.EMPTY;
}