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.mongodb.hadoop.examples.wordcount.split.WordCountSplitTest.java

@Override
public int run(String[] args) throws Exception {
    final Configuration conf = getConf();
    boolean useQuery = false;
    for (int i = 0; i < args.length; i++) {
        final String argi = args[i];
        if (argi.equals("--use-query"))
            useQuery = true;//from  www . j a  v  a 2  s  .co  m
        else {
            throw new IllegalArgumentException(argi);
        }
    }

    if (useQuery) {
        //NOTE: must do this BEFORE Job is created
        final MongoConfig mongo_conf = new MongoConfig(conf);
        com.mongodb.BasicDBObject query = new com.mongodb.BasicDBObject();
        query.put("num", new com.mongodb.BasicDBObject(Collections.singletonMap("$mod", new int[] { 2, 0 })));
        System.out.println(" --- setting query on num");
        mongo_conf.setQuery(query);
        System.out.println(" --- query is: " + mongo_conf.getQuery());
    }

    final com.mongodb.MongoURI outputUri = MongoConfigUtil.getOutputURI(conf);
    if (outputUri == null)
        throw new IllegalStateException("output uri is not set");
    if (MongoConfigUtil.getInputURI(conf) == null)
        throw new IllegalStateException("input uri is not set");
    final String outputCollectionName = outputUri.getCollection();

    final Job job = new Job(conf, "word count " + outputCollectionName);

    job.setJarByClass(WordCountSplitTest.class);

    job.setMapperClass(TokenizerMapper.class);

    job.setCombinerClass(IntSumReducer.class);
    job.setReducerClass(IntSumReducer.class);

    job.setOutputKeyClass(Text.class);
    job.setOutputValueClass(IntWritable.class);

    job.setInputFormatClass(MongoInputFormat.class);
    job.setOutputFormatClass(MongoOutputFormat.class);

    final long start = System.currentTimeMillis();
    System.out
            .println(" ----------------------- running test " + outputCollectionName + " --------------------");
    try {
        boolean result = job.waitForCompletion(true);
        System.out.println("job.waitForCompletion( true ) returned " + result);
    } catch (Exception e) {
        System.err.println("job.waitForCompletion( true ) threw Exception");
        e.printStackTrace();
        return 1;
    }
    final long end = System.currentTimeMillis();
    final float seconds = ((float) (end - start)) / 1000;
    java.text.NumberFormat nf = java.text.NumberFormat.getInstance();
    nf.setMaximumFractionDigits(3);
    System.out.println("finished run in " + nf.format(seconds) + " seconds");

    com.mongodb.Mongo m = new com.mongodb.Mongo(outputUri);
    com.mongodb.DB db = m.getDB(outputUri.getDatabase());
    com.mongodb.DBCollection coll = db.getCollection(outputCollectionName);
    com.mongodb.BasicDBObject query = new com.mongodb.BasicDBObject();
    query.put("_id", "the");
    com.mongodb.DBCursor cur = coll.find(query);
    if (!cur.hasNext())
        System.out.println("FAILURE: could not find count of \'the\'");
    else
        System.out.println("'the' count: " + cur.next());

    return 0; //is the return value supposed to be the program exit code?

    //        if (! result)
    //           System.exit(  1 );
}

From source file:edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis.java

@Override
protected List<Tick> refreshTicksHorizontal(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List<Tick> result = new ArrayList<Tick>();
    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);/*from  w  ww .ja v a2 s . c  o  m*/

    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, edge);
    }

    TickUnit tu = getTickUnit();
    double size = tu.getSize();
    int count = this.tickCount != null ? this.tickCount : calculateVisibleTickCount();
    double lowestTickValue = this.lowestTickValue != null ? this.lowestTickValue
            : calculateLowestVisibleTickValue();

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        int minorTickSpaces = getMinorTickCount();

        if (minorTickSpaces <= 0) {
            minorTickSpaces = tu.getMinorTickCount();
        }

        for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
            double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces;

            if (getRange().contains(minorTickValue)) {
                result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                        TextAnchor.CENTER, 0.0));
            }
        }

        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            String tickLabel = tickValueToLabelMapping.get(currentTickValue);

            if (tickLabel == null) {
                NumberFormat formatter = getNumberFormatOverride();

                if (formatter != null) {
                    tickLabel = formatter.format(currentTickValue);
                } else {
                    tickLabel = getTickUnit().valueToString(currentTickValue);
                }
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;

            if (isVerticalTickLabels()) {
                anchor = TextAnchor.CENTER_RIGHT;
                rotationAnchor = TextAnchor.CENTER_RIGHT;

                if (edge == RectangleEdge.TOP) {
                    angle = Math.PI / 2.0;
                } else {
                    angle = -Math.PI / 2.0;
                }
            } else {
                if (edge == RectangleEdge.TOP) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                } else {
                    anchor = TextAnchor.TOP_CENTER;
                    rotationAnchor = TextAnchor.TOP_CENTER;
                }
            }

            Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle);
            result.add(tick);
            double nextTickValue = lowestTickValue + ((i + 1) * size);

            for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
                double minorTickValue = currentTickValue
                        + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces;

                if (getRange().contains(minorTickValue)) {
                    result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                            TextAnchor.CENTER, 0.0));
                }
            }
        }
    }

    return result;
}

From source file:com.zte.ums.zenap.itm.agent.plugin.linux.util.Calculator.java

public String calculateItem(Map variables, String formula) throws MonitorException {

    Set vKeySet = variables.keySet();
    Object[] keys = vKeySet.toArray();
    Arrays.sort(keys);//from w  w  w. j  a  va2  s .  c om
    JexlContext jexlContext = new MapContext();
    for (int i = keys.length - 1; i >= 0; i--) {
        String s = keys[i].toString();
        String s1 = s.replace('.', 'a');
        formula = formula.replaceAll(s, s1);
        jexlContext.set(s1, variables.get(s));
    }

    try {
        while (true) {
            int eIndex = formula.indexOf("E");
            if (eIndex == -1) {
                break;
            }
            int startIndex = getBackwardNumIndex(formula, eIndex);
            int endIndex = getForwardNumIndex(formula, eIndex);
            String eNum = formula.substring(eIndex + 1, endIndex);
            String tenNumString = null;
            int num = Integer.parseInt(eNum);
            if (num > 5) {
                int tenNum = 1;
                for (int i = 0; i < (num - 5); i++) {
                    tenNum = tenNum * 10;
                }
                tenNumString = "100000.0 * " + Integer.toString(tenNum);
            } else if (num > 0) {
                int tenNum = 1;
                for (int i = 0; i < num; i++) {
                    tenNum = tenNum * 10;
                }
                tenNumString = Integer.toString(tenNum);
            } else if (num < 0) {
                double tenNum = 1;
                for (int i = 0; i > num; i--) {
                    tenNum = tenNum * 0.1;
                }
                tenNumString = Double.toString(tenNum);
            }
            String variable = formula.substring(startIndex, endIndex);
            String headVariable = formula.substring(startIndex, eIndex);
            formula = formula.replaceFirst(variable, "(" + headVariable + " * " + tenNumString + ")");
        }
        JexlEngine jexlEngine = new JexlEngine();
        Expression expression = jexlEngine.createExpression(formula);
        Object result = expression.evaluate(jexlContext);
        if (result instanceof Double) {
            Double dd = (Double) result;

            NumberFormat formater = new DecimalFormat("#.00");
            formater.setRoundingMode(RoundingMode.HALF_UP);
            return formater.format(dd);
        }
        return result.toString();
    } catch (Exception e) {
        throw new MonitorException("Error!Something wrong happened! ", e);
    }
}

From source file:edu.jhuapl.graphs.jfreechart.utils.CustomLabelNumberAxis.java

@Override
protected List<Tick> refreshTicksVertical(Graphics2D g2, Rectangle2D dataArea, RectangleEdge edge) {
    List<Tick> result = new ArrayList<Tick>();
    Font tickLabelFont = getTickLabelFont();
    g2.setFont(tickLabelFont);//w  w w .  ja  va 2 s  .  c o  m

    if (isAutoTickUnitSelection()) {
        selectAutoTickUnit(g2, dataArea, edge);
    }

    TickUnit tu = getTickUnit();
    double size = tu.getSize();
    int count = this.tickCount != null ? this.tickCount : calculateVisibleTickCount();
    double lowestTickValue = this.lowestTickValue != null ? this.lowestTickValue
            : calculateLowestVisibleTickValue();

    if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
        int minorTickSpaces = getMinorTickCount();

        if (minorTickSpaces <= 0) {
            minorTickSpaces = tu.getMinorTickCount();
        }

        for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
            double minorTickValue = lowestTickValue - size * minorTick / minorTickSpaces;

            if (getRange().contains(minorTickValue)) {
                result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                        TextAnchor.CENTER, 0.0));
            }
        }

        for (int i = 0; i < count; i++) {
            double currentTickValue = lowestTickValue + (i * size);
            String tickLabel = tickValueToLabelMapping.get(currentTickValue);

            if (tickLabel == null) {
                NumberFormat formatter = getNumberFormatOverride();

                if (formatter != null) {
                    tickLabel = formatter.format(currentTickValue);
                } else {
                    tickLabel = getTickUnit().valueToString(currentTickValue);
                }
            }

            TextAnchor anchor = null;
            TextAnchor rotationAnchor = null;
            double angle = 0.0;

            if (isVerticalTickLabels()) {
                if (edge == RectangleEdge.LEFT) {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = -Math.PI / 2.0;
                } else {
                    anchor = TextAnchor.BOTTOM_CENTER;
                    rotationAnchor = TextAnchor.BOTTOM_CENTER;
                    angle = Math.PI / 2.0;
                }
            } else {
                if (edge == RectangleEdge.LEFT) {
                    anchor = TextAnchor.CENTER_RIGHT;
                    rotationAnchor = TextAnchor.CENTER_RIGHT;
                } else {
                    anchor = TextAnchor.CENTER_LEFT;
                    rotationAnchor = TextAnchor.CENTER_LEFT;
                }
            }

            Tick tick = new NumberTick(new Double(currentTickValue), tickLabel, anchor, rotationAnchor, angle);
            result.add(tick);
            double nextTickValue = lowestTickValue + ((i + 1) * size);

            for (int minorTick = 1; minorTick < minorTickSpaces; minorTick++) {
                double minorTickValue = currentTickValue
                        + (nextTickValue - currentTickValue) * minorTick / minorTickSpaces;

                if (getRange().contains(minorTickValue)) {
                    result.add(new NumberTick(TickType.MINOR, minorTickValue, "", TextAnchor.TOP_CENTER,
                            TextAnchor.CENTER, 0.0));
                }
            }
        }
    }

    return result;
}

From source file:clus.statistic.RegressionStatBinaryNomiss.java

public String getString(StatisticPrintInfo info) {
    NumberFormat fr = ClusFormat.SIX_AFTER_DOT;
    StringBuffer buf = new StringBuffer();
    buf.append("[");
    for (int i = 0; i < m_NbAttrs; i++) {
        if (i != 0)
            buf.append(",");
        buf.append(fr.format(getMean(i)));
    }/*www . j  ava2s . co  m*/
    buf.append("]");
    if (info.SHOW_EXAMPLE_COUNT) {
        buf.append(": ");
        buf.append(fr.format(m_SumWeight));
    }
    return buf.toString();
}

From source file:de.tor.tribes.util.bb.BasicFormatter.java

public String formatElements(List<C> pElements, boolean pExtended) {
    StringBuilder b = new StringBuilder(pElements.size() * 15);
    NumberFormat f = getNumberFormatter(pElements.size());
    String beforeList = getHeader();
    String listItemTemplate = getLineTemplate();
    String afterList = getFooter();
    String replacedStart = StringUtils.replaceEach(beforeList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedStart);/*w  ww .  j av a 2 s .  c o  m*/
    formatElementsCore(b, pElements, pExtended, listItemTemplate, f);
    String replacedEnd = StringUtils.replaceEach(afterList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedEnd);
    return b.toString();
}

From source file:de.tor.tribes.util.bb.DefStatsFormatter.java

@Override
public String formatElements(List<Stats> pElements, boolean pShowAll) {
    StringBuilder b = new StringBuilder();
    int cnt = 1;//w  ww .  j a  v  a2 s .c  o m
    NumberFormat f = getNumberFormatter(pElements.size());
    String beforeList = getHeader();
    String listItemTemplate = getLineTemplate();
    String afterList = getFooter();
    String replacedStart = StringUtils.replaceEach(beforeList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedStart);
    Collections.sort(pElements, Stats.BASH_DEF_COMPARATOR);
    int idx = 0;
    for (Stats s : pElements) {
        String[] replacements = getStatSpecificReplacements(s);
        String itemLine = StringUtils.replaceEach(listItemTemplate, STAT_SPECIFIC_VARIABLES, replacements);
        itemLine = StringUtils.replaceEach(itemLine, new String[] { ELEMENT_ID, ELEMENT_COUNT },
                new String[] { f.format(cnt), f.format(pElements.size()) });
        b.append(itemLine).append("\n");
        cnt++;
        idx++;
        if (idx == 10 && !pShowAll) {
            //show only top10
            break;
        }
    }
    String replacedEnd = StringUtils.replaceEach(afterList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedEnd);
    return b.toString();
}

From source file:de.tor.tribes.util.bb.KillStatsFormatter.java

@Override
public String formatElements(List<Stats> pElements, boolean pShowAll) {
    StringBuilder b = new StringBuilder();
    int cnt = 1;//  w w  w. ja  v  a 2  s . c  o m
    NumberFormat f = getNumberFormatter(pElements.size());
    String beforeList = getHeader();
    String listItemTemplate = getLineTemplate();
    String afterList = getFooter();
    String replacedStart = StringUtils.replaceEach(beforeList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedStart);
    Collections.sort(pElements, Stats.BASH_OFF_COMPARATOR);
    int idx = 0;
    for (Stats s : pElements) {
        String[] replacements = getStatSpecificReplacements(s);
        String itemLine = StringUtils.replaceEach(listItemTemplate, STAT_SPECIFIC_VARIABLES, replacements);
        itemLine = StringUtils.replaceEach(itemLine, new String[] { ELEMENT_ID, ELEMENT_COUNT },
                new String[] { f.format(cnt), f.format(pElements.size()) });
        b.append(itemLine).append("\n");
        idx++;
        if (idx == 10 && !pShowAll) {
            //show only top10
            break;
        }
        cnt++;
    }
    String replacedEnd = StringUtils.replaceEach(afterList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedEnd);
    return b.toString();
}

From source file:io.jcml.gephi.plugins.abcd.ABCD.java

@Override
public String getReport() {
    String report = "";

    //Distribution series
    XYSeries cSeries = ChartUtils.createXYSeries(countsDist, "Friendship Scores Distribution");

    XYSeriesCollection dataset1 = new XYSeriesCollection();
    dataset1.addSeries(cSeries);//from   w  w  w .  j a va2s.c  o  m

    JFreeChart chart1 = ChartFactory.createXYLineChart("Friendship Scores Distribution", "Value", "Count",
            dataset1, PlotOrientation.VERTICAL, true, false, false);
    chart1.removeLegend();
    ChartUtils.decorateChart(chart1);
    ChartUtils.scaleChart(chart1, cSeries, false);
    String countsImageFile = ChartUtils.renderChart(chart1, "scores-distribution.png");

    NumberFormat f = new DecimalFormat("#0.000");

    report = "<HTML> <BODY> <h1>ABCD Report </h1> " + "<hr>" + "<br> <h2> Results: </h2>" + "Average score: "
            + f.format(avgFriendship) + "<br /><br />" + countsImageFile + "</BODY></HTML>";

    return report;
}

From source file:de.tor.tribes.util.bb.PointStatsFormatter.java

@Override
public String formatElements(List<Stats> pElements, boolean pShowAll) {
    StringBuilder b = new StringBuilder();
    int cnt = 1;/*from  w w w . j a  v  a 2s.  c o  m*/
    NumberFormat f = getNumberFormatter(pElements.size());
    String beforeList = getHeader();
    String listItemTemplate = getLineTemplate();
    String afterList = getFooter();
    String replacedStart = StringUtils.replaceEach(beforeList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedStart);
    Collections.sort(pElements, Stats.POINTS_COMPARATOR);
    int idx = 0;
    for (Stats s : pElements) {
        String[] replacements = getStatSpecificReplacements(s);
        String itemLine = StringUtils.replaceEach(listItemTemplate, STAT_SPECIFIC_VARIABLES, replacements);
        itemLine = StringUtils.replaceEach(itemLine, new String[] { ELEMENT_ID, ELEMENT_COUNT },
                new String[] { f.format(cnt), f.format(pElements.size()) });
        b.append(itemLine).append("\n");
        cnt++;
        idx++;
        if (idx == 10 && !pShowAll) {
            //show only top10
            break;
        }
    }
    String replacedEnd = StringUtils.replaceEach(afterList, new String[] { ELEMENT_COUNT },
            new String[] { f.format(pElements.size()) });
    b.append(replacedEnd);
    return b.toString();
}