Example usage for java.text NumberFormat getInstance

List of usage examples for java.text NumberFormat getInstance

Introduction

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

Prototype

public static NumberFormat getInstance(Locale inLocale) 

Source Link

Document

Returns a general-purpose number format for the specified locale.

Usage

From source file:de.dekarlab.moneybuilder.view.AnalyticsView.java

/**
 * Create pie chart./*w  w  w .ja  v  a2s.  c o m*/
 * 
 * @param dataset
 * @param title
 * @return
 */
protected JFreeChart createLineChart(final CategoryDataset dataset, final String title) {
    final JFreeChart chart = ChartFactory.createLineChart("", // chart title
            App.getGuiProp("report.period.lbl"), // domain axis label
            App.getGuiProp("report.value.lbl"), // range axis label
            dataset, // data
            PlotOrientation.VERTICAL, // orientation
            true, // include legend
            true, // tooltips
            false // urls
    );
    final CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setNoDataMessage(App.getGuiProp("report.nodata.msg"));
    plot.setBackgroundPaint(Color.white);
    plot.setBackgroundPaint(Color.white);
    ((NumberAxis) plot.getRangeAxis()).setAutoRangeIncludesZero(false);
    ((CategoryAxis) plot.getDomainAxis()).setMaximumCategoryLabelLines(10);
    ((CategoryAxis) plot.getDomainAxis()).setCategoryLabelPositions(CategoryLabelPositions.DOWN_90);
    plot.setDomainGridlinesVisible(true);
    plot.setDomainGridlinePaint(Color.gray);
    plot.setRangeGridlinePaint(Color.gray);
    plot.setRangeGridlinesVisible(true);
    plot.setRangeZeroBaselinePaint(Color.black);
    plot.setRangeZeroBaselineVisible(true);
    int color = 0;
    CategoryItemRenderer renderer = plot.getRenderer();
    for (int ser = 0; ser < dataset.getColumnCount(); ser++) {
        renderer.setSeriesPaint(ser, COLORS[color]);
        renderer.setSeriesStroke(ser, new BasicStroke(4));
        StandardCategoryItemLabelGenerator gen = new StandardCategoryItemLabelGenerator("{2}",
                NumberFormat.getInstance(Locale.GERMAN)) {
            private static final long serialVersionUID = 1L;

            public String generateLabel(CategoryDataset dataset, int series, int item) {
                if (item % 3 == 0) {
                    return super.generateLabelString(dataset, series, item);
                } else {
                    return null;
                }
            }
        };

        renderer.setSeriesItemLabelGenerator(ser, gen);
        renderer.setSeriesItemLabelsVisible(ser, true);

        color++;
        if (COLORS.length == color) {
            color = 0;
        }
    }
    return chart;
}

From source file:desmoj.extensions.grafic.util.Plotter.java

/**
 * Build a JPanel with a histogram plot of a desmoJ histogram dataset
* In the case histogram.getShowTimeSpansInReport() the data values are interpreted as
* a timespan in a appropriate time unit. 
 * @param histogram      desmoJ histogram dataset
 * @return/*from ww  w.  j  a  v a  2s. c  om*/
 */
private JPanel getHistogramPlot(Histogram histogram) {
    JFreeChart chart;
    NumberFormat formatter = NumberFormat.getInstance(locale);
    HistogramDataSetAdapter dataSet = new HistogramDataSetAdapter(histogram, locale);
    String title = histogram.getName();
    if (histogram.getDescription() != null)
        title = histogram.getDescription();
    String xLabel = dataSet.getCategoryAxisLabel();
    String yLabel = dataSet.getObservationAxisLabel();
    chart = ChartFactory.createBarChart(title, xLabel, yLabel, dataSet, PlotOrientation.VERTICAL, false, true,
            false);
    chart.setBackgroundPaint(Color.white);

    CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
    categoryplot.setBackgroundPaint(Color.lightGray);
    categoryplot.setRangeGridlinePaint(Color.white);
    categoryplot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_LEFT);

    BarRenderer barrenderer = (BarRenderer) categoryplot.getRenderer();
    barrenderer.setBaseItemLabelsVisible(true);
    StandardCategoryItemLabelGenerator generator = new StandardCategoryItemLabelGenerator("{2}", formatter);
    barrenderer.setBaseItemLabelGenerator(generator);

    CategoryAxis categoryaxis = categoryplot.getDomainAxis();
    //categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.DOWN_45);
    categoryaxis.setMaximumCategoryLabelLines(4);

    NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
    numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    //numberaxis.setUpperMargin(0.1D);
    numberaxis.setNumberFormatOverride(formatter);

    return new ChartPanel(chart);
}

From source file:com.rapidminer.tools.Tools.java

public static void setFormatLocale(Locale locale) {
    FORMAT_LOCALE = locale;/*from www.  j a  va 2  s .co  m*/
    NUMBER_FORMAT = NumberFormat.getInstance(locale);
    INTEGER_FORMAT = NumberFormat.getIntegerInstance(locale);
    PERCENT_FORMAT = NumberFormat.getPercentInstance(locale);
    FORMAT_SYMBOLS = new DecimalFormatSymbols(locale);
}

From source file:net.sourceforge.eclipsetrader.opentick.Feed.java

public void snapshot() {
    SimpleDateFormat usDateTimeParser = new SimpleDateFormat("MM/dd/yyyy h:mma");
    SimpleDateFormat usDateParser = new SimpleDateFormat("MM/dd/yyyy");
    SimpleDateFormat usTimeParser = new SimpleDateFormat("h:mma");
    NumberFormat numberFormat = NumberFormat.getInstance(Locale.US);

    // Builds the url for quotes download
    String host = "quote.yahoo.com";
    StringBuffer url = new StringBuffer("http://" + host + "/download/javasoft.beans?symbols=");
    for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
        Security security = (Security) iter.next();
        url = url.append(security.getCode() + "+");
    }/*  w w  w  .  j a v a  2 s .  c  o m*/
    if (url.charAt(url.length() - 1) == '+')
        url.deleteCharAt(url.length() - 1);
    url.append("&format=sl1d1t1c1ohgvbap");

    // Read the last prices
    String line = "";
    try {
        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

        BundleContext context = OpenTickPlugin.getDefault().getBundle().getBundleContext();
        ServiceReference reference = context.getServiceReference(IProxyService.class.getName());
        if (reference != null) {
            IProxyService proxy = (IProxyService) context.getService(reference);
            IProxyData data = proxy.getProxyDataForHost(host, IProxyData.HTTP_PROXY_TYPE);
            if (data != null) {
                if (data.getHost() != null)
                    client.getHostConfiguration().setProxy(data.getHost(), data.getPort());
                if (data.isRequiresAuthentication())
                    client.getState().setProxyCredentials(AuthScope.ANY,
                            new UsernamePasswordCredentials(data.getUserId(), data.getPassword()));
            }
        }

        HttpMethod method = new GetMethod(url.toString());
        method.setFollowRedirects(true);
        client.executeMethod(method);

        BufferedReader in = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        while ((line = in.readLine()) != null) {
            String[] item = line.split(",");
            if (line.indexOf(";") != -1)
                item = line.split(";");

            Double open = null, high = null, low = null, close = null;
            Quote quote = new Quote();

            // 2 = Date
            // 3 = Time
            try {
                GregorianCalendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"), Locale.US);
                usDateTimeParser.setTimeZone(c.getTimeZone());
                usDateParser.setTimeZone(c.getTimeZone());
                usTimeParser.setTimeZone(c.getTimeZone());

                String date = stripQuotes(item[2]);
                if (date.indexOf("N/A") != -1)
                    date = usDateParser.format(Calendar.getInstance().getTime());
                String time = stripQuotes(item[3]);
                if (time.indexOf("N/A") != -1)
                    time = usTimeParser.format(Calendar.getInstance().getTime());
                c.setTime(usDateTimeParser.parse(date + " " + time));
                c.setTimeZone(TimeZone.getDefault());
                quote.setDate(c.getTime());
            } catch (Exception e) {
                System.out.println(e.getMessage() + ": " + line);
            }
            // 1 = Last price or N/A
            if (item[1].equalsIgnoreCase("N/A") == false)
                quote.setLast(numberFormat.parse(item[1]).doubleValue());
            // 4 = Change
            // 5 = Open
            if (item[5].equalsIgnoreCase("N/A") == false)
                open = new Double(numberFormat.parse(item[5]).doubleValue());
            // 6 = Maximum
            if (item[6].equalsIgnoreCase("N/A") == false)
                high = new Double(numberFormat.parse(item[6]).doubleValue());
            // 7 = Minimum
            if (item[7].equalsIgnoreCase("N/A") == false)
                low = new Double(numberFormat.parse(item[7]).doubleValue());
            // 8 = Volume
            if (item[8].equalsIgnoreCase("N/A") == false)
                quote.setVolume(numberFormat.parse(item[8]).intValue());
            // 9 = Bid Price
            if (item[9].equalsIgnoreCase("N/A") == false)
                quote.setBid(numberFormat.parse(item[9]).doubleValue());
            // 10 = Ask Price
            if (item[10].equalsIgnoreCase("N/A") == false)
                quote.setAsk(numberFormat.parse(item[10]).doubleValue());
            // 11 = Close Price
            if (item[11].equalsIgnoreCase("N/A") == false)
                close = new Double(numberFormat.parse(item[11]).doubleValue());

            // 0 = Code
            String symbol = stripQuotes(item[0]);
            for (Iterator iter = subscribedSecurities.iterator(); iter.hasNext();) {
                Security security = (Security) iter.next();
                if (symbol.equalsIgnoreCase(security.getCode()))
                    security.setQuote(quote, open, high, low, close);
            }
        }
        in.close();
    } catch (Exception e) {
        System.out.println(e.getMessage() + ": " + line);
        e.printStackTrace();
    }
}

From source file:com.jaspersoft.studio.editor.preview.input.BigNumericInput.java

public void updateInput() {
    if (num.isDisposed())
        return;//from  ww  w  . j  a v a  2  s .  c o  m
    Object value = params.get(param.getName());
    if (value != null && value instanceof String)
        value = getNumber((String) value);
    if (value != null && value instanceof Number) {
        NumberFormat nformat = NumberFormat.getInstance(Locale.US);
        nformat.setGroupingUsed(false);
        num.setText(nformat.format(value));
    } else
        num.setText("");
    setDecoratorNullable(param);
}

From source file:org.drools.planner.benchmark.core.report.BenchmarkReport.java

private void writeBestScoreSummaryCharts() {
    // Each scoreLevel has it's own dataset and chartFile
    List<DefaultCategoryDataset> datasetList = new ArrayList<DefaultCategoryDataset>(CHARTED_SCORE_LEVEL_SIZE);
    for (SolverBenchmark solverBenchmark : plannerBenchmark.getSolverBenchmarkList()) {
        String solverLabel = solverBenchmark.getNameWithFavoriteSuffix();
        for (SingleBenchmark singleBenchmark : solverBenchmark.getSingleBenchmarkList()) {
            String planningProblemLabel = singleBenchmark.getProblemBenchmark().getName();
            if (singleBenchmark.isSuccess()) {
                double[] levelValues = singleBenchmark.getScore().toDoubleLevels();
                for (int i = 0; i < levelValues.length && i < CHARTED_SCORE_LEVEL_SIZE; i++) {
                    if (i >= datasetList.size()) {
                        datasetList.add(new DefaultCategoryDataset());
                    }/*from  w w  w .  j a v a2 s  . co m*/
                    datasetList.get(i).addValue(levelValues[i], solverLabel, planningProblemLabel);
                }
            }
        }
    }
    bestScoreSummaryChartFileList = new ArrayList<File>(datasetList.size());
    int scoreLevelIndex = 0;
    for (DefaultCategoryDataset dataset : datasetList) {
        CategoryPlot plot = createBarChartPlot(dataset, "Score level " + scoreLevelIndex,
                NumberFormat.getInstance(locale));
        JFreeChart chart = new JFreeChart("Best score level " + scoreLevelIndex + " summary (higher is better)",
                JFreeChart.DEFAULT_TITLE_FONT, plot, true);
        bestScoreSummaryChartFileList
                .add(writeChartToImageFile(chart, "bestScoreSummaryLevel" + scoreLevelIndex));
        scoreLevelIndex++;
    }
}

From source file:com.jeeframework.util.validate.GenericTypeValidator.java

/**
 *  Checks if the value can safely be converted to a double primitive.
 *
 *@param  value   The value validation is being performed on.
 *@param  locale  The locale to use to parse the number (system default if
 *      null)/*from  w w w  . j a  va 2s .  co m*/
 *@return the converted Double value.
 */
public static Double formatDouble(String value, Locale locale) {
    Double result = null;

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getInstance(locale);
        } else {
            formatter = NumberFormat.getInstance(Locale.getDefault());
        }
        ParsePosition pos = new ParsePosition(0);
        Number num = formatter.parse(value, pos);

        // If there was no error      and we used the whole string
        if (pos.getErrorIndex() == -1 && pos.getIndex() == value.length()) {
            if (num.doubleValue() >= (Double.MAX_VALUE * -1) && num.doubleValue() <= Double.MAX_VALUE) {
                result = new Double(num.doubleValue());
            }
        }
    }

    return result;
}

From source file:javadz.beanutils.locale.converters.StringLocaleConverter.java

/**
 * Make an instance of DecimalFormat./*  ww  w.java 2  s .  com*/
 *
 * @param locale The locale
 * @param pattern The pattern is used for the convertion
 * @return The format for the locale and pattern
 *
 * @exception ConversionException if conversion cannot be performed
 *  successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
private DecimalFormat getDecimalFormat(Locale locale, String pattern) {

    DecimalFormat numberFormat = (DecimalFormat) NumberFormat.getInstance(locale);

    // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            numberFormat.applyLocalizedPattern(pattern);
        } else {
            numberFormat.applyPattern(pattern);
        }
    } else {
        log.debug("No pattern provided, using default.");
    }

    return numberFormat;
}

From source file:com.hichinaschool.flashcards.libanki.Utils.java

public static String fmtDouble(Double value, int point) {
    // only retrieve the number format the first time
    if (mCurrentNumberFormat == null) {
        mCurrentNumberFormat = NumberFormat.getInstance(Locale.getDefault());
    }/*from   w w  w  .j av  a2  s . com*/
    mCurrentNumberFormat.setMaximumFractionDigits(point);
    return mCurrentNumberFormat.format(value);
}

From source file:net.sf.morph.transform.converters.TextToNumberConverter.java

/**
 * {@inheritDoc}//from ww  w . j ava2  s  .  c  om
 */
protected Object convertImpl(Class destinationClass, Object source, Locale locale) throws Exception {

    if (ObjectUtils.isEmpty(source)) {
        return null;
    }
    // convert the source to a String
    String string = (String) getTextConverter().convert(String.class, source, locale);

    //         // if a custom numberFormat has been specified, ues that for the
    //         // conversion
    //         if (numberFormat != null) {
    //            Number number;
    //            synchronized (numberFormat) {
    //               number = numberFormat.parse(string);
    //            }
    //
    //            // convert the number to the destination class requested
    //            return getNumberConverter().convert(destinationClass, number,
    //               locale);
    //         }

    StringBuffer charactersToParse =
            // remove characters that should be ignored, such as currency symbols
            // when currency handling is set to CURRENCY_IGNORE
            removeIgnoredCharacters(string, locale);

    // keep track of whether the conversion result needs to be negated
    // before it is returned
    boolean negate = handleParenthesesNegation(charactersToParse, locale);
    negate = negate || handleNegativeSignNegation(charactersToParse, locale);

    NumberFormat format = null;
    ParsePosition position = null;
    Number number = null;
    Object returnVal = null;
    String stringToParse = charactersToParse.toString();

    // could not get this to work for some reason
    //         // try to do the conversion assuming the source is a currency value
    //         format = NumberFormat.getCurrencyInstance(locale);
    //         position = new ParsePosition(0);
    //         number = format.parse(stringWithoutIgnoredSymbolsStr, position);
    //         if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) {
    //            // convert the number to the destination class requested
    //            returnVal = getNumberConverter().convert(destinationClass, number,
    //               locale);
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Successfully parsed '" + source + "' as a currency value of " + returnVal);
    //            }
    //            return returnVal;
    //         }
    //         else {
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Could not perform conversion of '" + source + "' by treating the source as a currency value");
    //            }
    //         }

    // try to do the conversion to decimal assuming the source is a
    // percentage
    if (getPercentageHandling() == PERCENTAGE_CONVERT_TO_DECIMAL) {
        format = NumberFormat.getPercentInstance(locale);
        position = new ParsePosition(0);
        number = format.parse(stringToParse, position);
        if (isParseSuccessful(stringToParse, position)) {
            // negate the number if needed
            returnVal = negateIfNecessary(number, negate, locale);
            // convert the number to the destination class requested
            returnVal = getNumberConverter().convert(destinationClass, returnVal, locale);
            if (logger.isDebugEnabled()) {
                logger.debug("Successfully parsed '" + source + "' as a percentage with value " + returnVal);
            }
            return returnVal;
        }
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Could not perform conversion of '" + source + "' by treating the source as a percentage");
        }
    }

    // try to do the conversion as a regular number
    format = NumberFormat.getInstance(locale);
    position = new ParsePosition(0);
    number = format.parse(stringToParse, position);
    if (isParseSuccessful(stringToParse, position)) {
        // negate the number if needed
        returnVal = negateIfNecessary(number, negate, locale);
        // convert the number to the destination class requested
        returnVal = getNumberConverter().convert(destinationClass, returnVal, locale);
        if (logger.isDebugEnabled()) {
            logger.debug("Successfully parsed '" + source + "' as a number or currency value of " + returnVal);
        }
        return returnVal;
    }
    if (logger.isDebugEnabled()) {
        logger.debug("Could not perform conversion of '" + source
                + "' by treating the source as a regular number or currency value");
    }

    //         // if the first character of the string is a currency symbol
    //         if (Character.getType(stringWithoutIgnoredSymbolsStr.charAt(0)) == Character.CURRENCY_SYMBOL) {
    //            // try doing the conversion as a regular number by stripping off the first character
    //            format = NumberFormat.getInstance(locale);
    //            position = new ParsePosition(1);
    //            number = format.parse(stringWithoutIgnoredSymbolsStr, position);
    //            if (isParseSuccessful(stringWithoutIgnoredSymbolsStr, position)) {
    //               // convert the number to the destination class requested
    //               return getNumberConverter().convert(destinationClass, number,
    //                  locale);
    //            }
    //            if (logger.isDebugEnabled()) {
    //               logger.debug("Could not perform conversion of '" + source + "' by stripping the first character and treating as a normal number");
    //            }
    //         }

    throw new TransformationException(destinationClass, source);
}