Example usage for java.text NumberFormat getNumberInstance

List of usage examples for java.text NumberFormat getNumberInstance

Introduction

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

Prototype

public static NumberFormat getNumberInstance(Locale inLocale) 

Source Link

Document

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

Usage

From source file:org.rhq.enterprise.gui.legacy.taglib.MetricDisplayTag.java

@Override
public int doEndTag() throws JspException {
    Locale userLocale = RequestUtils.retrieveUserLocale(pageContext, locale);
    if (unitIsSet) {
        setUnitVal((String) evalAttr("unit", unit_el, String.class));
    }//from w ww .  j ava2s  . c o  m

    if (defaultKeyIsSet) {
        setDefaultKeyVal((String) evalAttr("defaultKey", defaultKey_el, String.class));
    }

    // if the metric value is empty, converting to a Double will
    // give a value of 0.0. this makes it impossible for us to
    // distinguish further down the line whether the metric was
    // actually collected with a value of 0.0 or whether it was
    // not collected at all. therefore, we'll let metricVal be
    // null if the metric was not collected, and we'll check for
    // null later when handling the not-avail case.
    // PR: 7588
    String mval = (String) evalAttr("metric", metric_el, String.class);
    if ((mval != null) && !mval.equals("")) {
        setMetricVal(new Double(mval));
    }

    StringBuffer sb = new StringBuffer("<span");
    if (spanIsSet && (getSpan().length() > 0)) {
        setSpanVal((String) evalAttr("span", span_el, String.class));
        sb.append(" class=\"");
        sb.append(getSpanVal());
        sb.append("\"");
    }

    sb.append(">");

    if ((getMetricVal() == null) || (Double.isNaN(getMetricVal().doubleValue()) && defaultKeyIsSet)) {
        sb.append(RequestUtils.message(pageContext, bundle, userLocale.toString(), getDefaultKeyVal()));
    }

    // XXXX remove duplication with the metric decorator
    // and the UnitsConvert/UnitsFormat stuff
    else if (getUnitVal().equals("ms")) {
        NumberFormat f = NumberFormat.getNumberInstance(userLocale);
        f.setMinimumFractionDigits(3);
        f.setMaximumFractionDigits(3);
        String formatted = f.format(getMetricVal().doubleValue() / 1000);
        String[] args = new String[] { formatted };
        sb.append(RequestUtils.message(pageContext, bundle, userLocale.toString(), "metric.tag.units.s.arg",
                args));
    } else {
        MeasurementUnits units = MeasurementUnits.valueOf(getUnitVal());
        Double dataValue = getMetricVal();
        String formattedValue = MeasurementConverter.format(dataValue, units, true);

        sb.append(formattedValue);
    }

    sb.append("</span>");

    try {
        pageContext.getOut().print(sb.toString());
    } catch (IOException e) {
        log.debug("could not write output: ", e);
        throw new JspException("Could not access metrics tag");
    }

    release();
    return EVAL_PAGE;
}

From source file:com.bdaum.zoom.gps.internal.GpsUtilities.java

public static void getGeoAreas(IPreferenceStore preferenceStore, Collection<GeoArea> areas) {
    NumberFormat nf = NumberFormat.getNumberInstance(Locale.US);
    nf.setMaximumFractionDigits(8);/*w ww  .ja  va2  s  .c o  m*/
    nf.setGroupingUsed(false);
    String nogo = preferenceStore.getString(PreferenceConstants.NOGO);
    if (nogo != null) {
        int i = 0;
        double lat = 0, lon = 0, km = 0;
        String name = null;
        StringTokenizer st = new StringTokenizer(nogo, ";,", true); //$NON-NLS-1$
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            if (";".equals(s)) { //$NON-NLS-1$
                areas.add(new GeoArea(name, lat, lon, km));
                i = 0;
            } else if (",".equals(s)) //$NON-NLS-1$
                ++i;
            else
                try {
                    switch (i) {
                    case 0:
                        name = s;
                        break;
                    case 1:
                        lat = nf.parse(s).doubleValue();
                        break;
                    case 2:
                        lon = nf.parse(s).doubleValue();
                        break;
                    case 3:
                        km = nf.parse(s).doubleValue();
                        break;
                    }
                } catch (ParseException e) {
                    // do nothing
                }
        }
    }
}

From source file:org.openestate.io.core.NumberUtils.java

/**
 * Write a number into a string value./*from  w  w  w  . j  a v a 2s .c om*/
 *
 * @param value
 * the number to write
 *
 * @param integerDigits
 * maximal number of integer digits
 *
 * @param fractionDigits
 * maximal number of fraction digits
 *
 * @param locale
 * locale for decimal separator (using {@link Locale#ENGLISH} if null)
 *
 * @return
 * the formatted number
 */
public static String printNumber(Number value, int integerDigits, int fractionDigits, Locale locale) {
    if (value == null)
        return null;
    NumberFormat format = NumberFormat.getNumberInstance((locale != null) ? locale : Locale.ENGLISH);
    format.setMaximumIntegerDigits(integerDigits);
    format.setMaximumFractionDigits(fractionDigits);
    format.setMinimumFractionDigits(0);
    format.setGroupingUsed(false);
    return format.format(value);
}

From source file:name.gumartinm.weather.information.fragment.specific.SpecificFragment.java

private void updateUI(final Forecast forecastWeatherData, final int chosenDay) {

    // 1. Update units of measurement.
    final UnitsConversor tempUnitsConversor = new TempUnitsConversor(
            this.getActivity().getApplicationContext());
    final UnitsConversor windConversor = new WindUnitsConversor(this.getActivity().getApplicationContext());
    final UnitsConversor pressureConversor = new PressureUnitsConversor(
            this.getActivity().getApplicationContext());

    // 2. Formatters
    final DecimalFormat numberFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    numberFormatter.applyPattern("###.##");

    // 3. Prepare data for UI.
    final name.gumartinm.weather.information.model.forecastweather.List forecast = forecastWeatherData.getList()
            .get((chosenDay));//from w  w  w  .  j a  va 2  s . c  om

    final SimpleDateFormat dayFormatter = new SimpleDateFormat("EEEE - MMM d", Locale.US);
    final Calendar calendar = Calendar.getInstance();
    final Long forecastUNIXDate = (Long) forecast.getDt();
    calendar.setTimeInMillis(forecastUNIXDate * 1000L);
    final Date date = calendar.getTime();

    String tempMax = "";
    if (forecast.getTemp().getMax() != null) {
        double conversion = (Double) forecast.getTemp().getMax();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = numberFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    String tempMin = "";
    if (forecast.getTemp().getMin() != null) {
        double conversion = (Double) forecast.getTemp().getMin();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = numberFormatter.format(conversion) + tempUnitsConversor.getSymbol();
    }
    Bitmap picture;
    if ((forecast.getWeather().size() > 0) && (forecast.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(forecast.getWeather().get(0).getIcon()) != null)) {
        final String icon = forecast.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }

    String description = this.getString(R.string.text_field_description_when_error);
    if (forecast.getWeather().size() > 0) {
        description = forecast.getWeather().get(0).getDescription();
    }

    String humidityValue = "";
    if (forecast.getHumidity() != null) {
        final double conversion = (Double) forecast.getHumidity();
        humidityValue = numberFormatter.format(conversion);
    }
    String pressureValue = "";
    if (forecast.getPressure() != null) {
        double conversion = (Double) forecast.getPressure();
        conversion = pressureConversor.doConversion(conversion);
        pressureValue = numberFormatter.format(conversion);
    }
    String windValue = "";
    if (forecast.getSpeed() != null) {
        double conversion = (Double) forecast.getSpeed();
        conversion = windConversor.doConversion(conversion);
        windValue = numberFormatter.format(conversion);
    }
    String rainValue = "";
    if (forecast.getRain() != null) {
        final double conversion = (Double) forecast.getRain();
        rainValue = numberFormatter.format(conversion);
    }
    String cloudsValue = "";
    if (forecast.getRain() != null) {
        final double conversion = (Double) forecast.getClouds();
        cloudsValue = numberFormatter.format(conversion);
    }

    final String tempSymbol = tempUnitsConversor.getSymbol();
    String tempDay = "";
    if (forecast.getTemp().getDay() != null) {
        double conversion = (Double) forecast.getTemp().getDay();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempDay = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempMorn = "";
    if (forecast.getTemp().getMorn() != null) {
        double conversion = (Double) forecast.getTemp().getMorn();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMorn = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempEve = "";
    if (forecast.getTemp().getEve() != null) {
        double conversion = (Double) forecast.getTemp().getEve();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempEve = numberFormatter.format(conversion) + tempSymbol;
    }
    String tempNight = "";
    if (forecast.getTemp().getNight() != null) {
        double conversion = (Double) forecast.getTemp().getNight();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempNight = numberFormatter.format(conversion) + tempSymbol;
    }

    // 4. Update UI.
    this.getActivity().getActionBar().setSubtitle(dayFormatter.format(date).toUpperCase());

    final TextView tempMaxView = (TextView) getActivity().findViewById(R.id.weather_specific_temp_max);
    tempMaxView.setText(tempMax);
    final TextView tempMinView = (TextView) getActivity().findViewById(R.id.weather_specific_temp_min);
    tempMinView.setText(tempMin);
    final ImageView pictureView = (ImageView) getActivity().findViewById(R.id.weather_specific_picture);
    pictureView.setImageBitmap(picture);

    final TextView descriptionView = (TextView) getActivity().findViewById(R.id.weather_specific_description);
    descriptionView.setText(description);

    final TextView humidityValueView = (TextView) getActivity()
            .findViewById(R.id.weather_specific_humidity_value);
    humidityValueView.setText(humidityValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_pressure_value)).setText(pressureValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_pressure_units))
            .setText(pressureConversor.getSymbol());
    ((TextView) getActivity().findViewById(R.id.weather_specific_wind_value)).setText(windValue);
    ((TextView) getActivity().findViewById(R.id.weather_specific_wind_units))
            .setText(windConversor.getSymbol());
    final TextView rainValueView = (TextView) getActivity().findViewById(R.id.weather_specific_rain_value);
    rainValueView.setText(rainValue);
    final TextView cloudsValueView = (TextView) getActivity().findViewById(R.id.weather_specific_clouds_value);
    cloudsValueView.setText(cloudsValue);

    final TextView tempDayView = (TextView) getActivity().findViewById(R.id.weather_specific_day_temperature);
    tempDayView.setText(tempDay);
    final TextView tempMornView = (TextView) getActivity().findViewById(R.id.weather_specific_morn_temperature);
    tempMornView.setText(tempMorn);
    final TextView tempEveView = (TextView) getActivity().findViewById(R.id.weather_specific_eve_temperature);
    tempEveView.setText(tempEve);
    final TextView tempNightView = (TextView) getActivity()
            .findViewById(R.id.weather_specific_night_temperature);
    tempNightView.setText(tempNight);
}

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

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

    if (value != null) {
        NumberFormat formatter = null;
        if (locale != null) {
            formatter = NumberFormat.getNumberInstance(locale);
        } else {
            formatter = NumberFormat.getNumberInstance(Locale.getDefault());
        }
        formatter.setParseIntegerOnly(true);
        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() >= Integer.MIN_VALUE && num.doubleValue() <= Integer.MAX_VALUE) {
                result = new Integer(num.intValue());
            }
        }
    }

    return result;
}

From source file:it.eng.spagobi.engines.chart.bo.charttypes.barcharts.SimpleBar.java

public JFreeChart createChart(DatasetMap datasets) {
    logger.debug("IN");
    CategoryDataset dataset = (CategoryDataset) datasets.getDatasets().get("1");

    PlotOrientation plotOrientation = PlotOrientation.VERTICAL;
    if (horizontalView) {
        plotOrientation = PlotOrientation.HORIZONTAL;
    }//from  ww w  . ja  v a  2 s .  c o  m

    JFreeChart chart = ChartFactory.createBarChart(name, // chart title
            categoryLabel, // domain axis label
            valueLabel, // range axis label
            dataset, // data
            plotOrientation, // orientation
            false, // include legend
            true, // tooltips?
            false // URLs?
    );

    TextTitle title = setStyleTitle(name, styleTitle);
    chart.setTitle(title);
    if (subName != null && !subName.equals("")) {
        TextTitle subTitle = setStyleTitle(subName, styleSubTitle);
        chart.addSubtitle(subTitle);
    }

    // set the background color for the chart...
    chart.setBackgroundPaint(color);

    // get a reference to the plot for further customisation...
    CategoryPlot plot = (CategoryPlot) chart.getPlot();
    plot.setBackgroundPaint(Color.white);
    plot.setDomainGridlinePaint(Color.white);
    plot.setDomainGridlinesVisible(true);
    plot.setRangeGridlinePaint(Color.white);

    NumberFormat nf = NumberFormat.getNumberInstance(locale);

    // set the range axis to display integers only...
    NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
    rangeAxis.setLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setLabelPaint(styleXaxesLabels.getColor());
    rangeAxis
            .setTickLabelFont(new Font(styleXaxesLabels.getFontName(), Font.PLAIN, styleXaxesLabels.getSize()));
    rangeAxis.setTickLabelPaint(styleXaxesLabels.getColor());
    rangeAxis.setUpperMargin(0.10);
    rangeAxis.setNumberFormatOverride(nf);

    if (firstAxisLB != null && firstAxisUB != null) {
        rangeAxis.setLowerBound(firstAxisLB);
        rangeAxis.setUpperBound(firstAxisUB);
    }

    if (rangeIntegerValues == true) {
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
    } else
        rangeAxis.setStandardTickUnits(NumberAxis.createStandardTickUnits());

    if (rangeAxisLocation != null) {
        if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_LEFT);
        } else if (rangeAxisLocation.equalsIgnoreCase("BOTTOM_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.BOTTOM_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_RIGHT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_RIGHT);
        } else if (rangeAxisLocation.equalsIgnoreCase("TOP_OR_LEFT")) {
            plot.setRangeAxisLocation(0, AxisLocation.TOP_OR_LEFT);
        }
    }

    // disable bar outlines...
    BarRenderer renderer = (BarRenderer) plot.getRenderer();
    renderer.setDrawBarOutline(false);

    // add
    CategorySeriesLabelGenerator generator = new StandardCategorySeriesLabelGenerator("{0}");
    renderer.setLegendItemLabelGenerator(generator);

    if (maxBarWidth != null) {
        renderer.setMaximumBarWidth(maxBarWidth.doubleValue());
    }

    if (showValueLabels) {
        renderer.setBaseItemLabelsVisible(true);
        renderer.setBaseItemLabelGenerator(new FilterZeroStandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelFont(
                new Font(styleValueLabels.getFontName(), Font.PLAIN, styleValueLabels.getSize()));
        renderer.setBaseItemLabelPaint(styleValueLabels.getColor());

        //         if(valueLabelsPosition.equalsIgnoreCase("inside")){
        //         renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
        //         ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
        //         renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
        //         ItemLabelAnchor.CENTER, TextAnchor.BASELINE_LEFT));
        //         } else {
        //         renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
        //         ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
        //         renderer.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
        //         ItemLabelAnchor.OUTSIDE3, TextAnchor.BASELINE_LEFT));
        //         }

    }

    // PROVA LEGENDA      
    if (legend == true) {

        drawLegend(chart);

        /*BlockContainer wrapper = new BlockContainer(new BorderArrangement());
        wrapper.setFrame(new BlockBorder(1.0, 1.0, 1.0, 1.0));
                
        LabelBlock titleBlock = new LabelBlock("Legend Items:",
              new Font("SansSerif", Font.BOLD, 12));
        title.setPadding(5, 5, 5, 5);
        wrapper.add(titleBlock, RectangleEdge.TOP);
                
        LegendTitle legend = new LegendTitle(chart.getPlot());
        BlockContainer items = legend.getItemContainer();
        items.setPadding(2, 10, 5, 2);
        wrapper.add(items);
        legend.setWrapper(wrapper);
                
        if(legendPosition.equalsIgnoreCase("bottom")) legend.setPosition(RectangleEdge.BOTTOM);
        else if(legendPosition.equalsIgnoreCase("left")) legend.setPosition(RectangleEdge.LEFT);
        else if(legendPosition.equalsIgnoreCase("right")) legend.setPosition(RectangleEdge.RIGHT);
        else if(legendPosition.equalsIgnoreCase("top")) legend.setPosition(RectangleEdge.TOP);
        else legend.setPosition(RectangleEdge.BOTTOM);
                
        legend.setHorizontalAlignment(HorizontalAlignment.LEFT);
        chart.addSubtitle(legend);*/
    }

    int seriesN = dataset.getRowCount();

    // the order color vedctor overrides the color map!!

    if (orderColorVector != null && orderColorVector.size() > 0) {
        logger.debug("color serie by SERIES_ORDER_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            if (orderColorVector.get(i) != null) {
                Color color = orderColorVector.get(i);
                renderer.setSeriesPaint(i, color);
            }
        }
    } else if (colorMap != null) {
        logger.debug("color serie by SERIES_COLORS template specification");
        for (int i = 0; i < seriesN; i++) {
            String serieName = (String) dataset.getRowKey(i);
            String labelName = "";
            int index = -1;
            if (seriesCaptions != null && seriesCaptions.size() > 0) {
                labelName = serieName;
                serieName = (String) seriesCaptions.get(serieName);
                index = dataset.getRowIndex(labelName);
            } else
                index = dataset.getRowIndex(serieName);

            Color color = (Color) colorMap.get(serieName);
            if (color != null) {
                //renderer.setSeriesPaint(i, color);
                renderer.setSeriesPaint(index, color);
                renderer.setSeriesItemLabelFont(i,
                        new Font(defaultLabelsStyle.getFontName(), Font.PLAIN, defaultLabelsStyle.getSize()));
                renderer.setSeriesItemLabelPaint(i, defaultLabelsStyle.getColor());
            }
        }
    }

    CategoryAxis domainAxis = plot.getDomainAxis();
    domainAxis.setCategoryLabelPositions(CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0));
    domainAxis.setLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setLabelPaint(styleYaxesLabels.getColor());
    domainAxis
            .setTickLabelFont(new Font(styleYaxesLabels.getFontName(), Font.PLAIN, styleYaxesLabels.getSize()));
    domainAxis.setTickLabelPaint(styleYaxesLabels.getColor());
    domainAxis.setUpperMargin(0.10);
    logger.debug("OUT");
    return chart;

}

From source file:org.hyperic.hq.ui.taglib.MetricDisplayTag.java

public int doEndTag() throws JspException {
    Locale userLocale = TagUtils.getInstance().getUserLocale(pageContext, locale);

    if (unitIsSet) {
        setUnitVal(getUnit());//from ww w. ja v  a2 s  . c  om
    }

    if (defaultKeyIsSet) {
        setDefaultKeyVal(getDefaultKey());
    }

    // if the metric value is empty, converting to a Double will
    // give a value of 0.0. this makes it impossible for us to
    // distinguish further down the line whether the metric was
    // actually collected with a value of 0.0 or whether it was
    // not collected at all. therefore, we'll let metricVal be
    // null if the metric was not collected, and we'll check for
    // null later when handling the not-avail case.
    // PR: 7588
    String mval = getMetric();

    if (mval != null && !mval.equals("")) {
        setMetricVal(new Double(mval));
    }

    StringBuffer sb = new StringBuffer("<span");

    if (spanIsSet && getSpan().length() > 0) {
        setSpanVal(getSpan());
        sb.append(" class=\"");
        sb.append(getSpanVal());
        sb.append("\"");
    }

    sb.append(">");

    if (getMetricVal() == null || Double.isNaN(getMetricVal().doubleValue()) && defaultKeyIsSet) {
        sb.append(
                TagUtils.getInstance().message(pageContext, bundle, userLocale.toString(), getDefaultKeyVal()));
    }
    // XXXX remove duplication with the metric decorator
    // and the UnitsConvert/UnitsFormat stuff
    else if (getUnitVal().equals("ms")) {
        NumberFormat f = NumberFormat.getNumberInstance(userLocale);

        f.setMinimumFractionDigits(3);
        f.setMaximumFractionDigits(3);

        String formatted = f.format(getMetricVal().doubleValue() / 1000);
        String[] args = new String[] { formatted };

        sb.append(TagUtils.getInstance().message(pageContext, bundle, userLocale.toString(),
                "metric.tag.units.s.arg", args));
    } else {
        FormattedNumber f = UnitsConvert.convert(getMetricVal().doubleValue(), getUnitVal(), userLocale);

        sb.append(f.getValue());

        if (f.getTag() != null && f.getTag().length() > 0) {
            sb.append(" ").append(f.getTag());
        }
    }

    sb.append("</span>");

    try {
        pageContext.getOut().print(sb.toString());
    } catch (IOException e) {
        log.debug("could not write output: ", e);

        throw new JspException("Could not access metrics tag");
    }

    release();

    return EVAL_PAGE;
}

From source file:com.amagi82.kerbalspaceapp.Settings.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowTitleEnabled(true);
    getActionBar().setTitle(R.string.title_activity_settings);

    SeekBar clearance = (SeekBar) findViewById(R.id.seekBarClearance);
    SeekBar margins = (SeekBar) findViewById(R.id.seekBarMargins);
    SeekBar inclination = (SeekBar) findViewById(R.id.seekBarInclination);
    mClearance = (TextView) findViewById(R.id.tvClearance);
    mMargins = (TextView) findViewById(R.id.tvMargins);
    mInclination = (TextView) findViewById(R.id.tvInclination);
    chooseLanguage = (Spinner) findViewById(R.id.spinnerLanguages);

    SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
    mClearanceValue = prefs.getInt("mClearanceValue", 1000);
    mMarginsValue = prefs.getInt("mMarginsValue", 10);
    mInclinationValue = prefs.getInt("mInclinationValue", 30);
    chooseLanguage.setSelection(prefs.getInt("language", 0));

    // Set up spinner
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActionBar().getThemedContext(),
            R.array.languages, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    chooseLanguage.setAdapter(adapter);/*from w  w  w . jav a 2s  . co  m*/
    // @formatter:off
    if (Locale.getDefault().getLanguage().equals("en"))
        chooseLanguage.setSelection(0);
    if (Locale.getDefault().getLanguage().equals("fr"))
        chooseLanguage.setSelection(1);
    if (Locale.getDefault().getLanguage().equals("de"))
        chooseLanguage.setSelection(2);
    if (Locale.getDefault().getLanguage().equals("es"))
        chooseLanguage.setSelection(3);
    if (Locale.getDefault().getLanguage().equals("ru"))
        chooseLanguage.setSelection(4);

    // Set seekbar progress
    clearance.setProgress(mClearanceValue);
    margins.setProgress(mMarginsValue);
    inclination.setProgress(mInclinationValue);

    // Display values
    mClearance.setText(mClearanceValue + "m");
    mMargins.setText(mMarginsValue + "%");
    setInclinationText();

    clearance.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            String value = NumberFormat.getNumberInstance(Locale.getDefault()).format(progress);
            mClearance.setText(value + "m");
            mClearanceValue = progress;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    margins.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mMargins.setText(progress + "%");
            mMarginsValue = progress;
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    inclination.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            mInclinationValue = progress;
            setInclinationText();
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
    chooseLanguage.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            language = langCode[chooseLanguage.getSelectedItemPosition()];
            onConfigurationChanged(getResources().getConfiguration());
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

}

From source file:com.expressui.core.view.field.format.DefaultFormats.java

/**
 * Gets number format, NumberFormat.getNumberInstance(), using current user's locale.
 *
 * @param defaultValueWhenEmpty when parsing Strings, returns this value when String is empty
 * @return default number format/*from  w ww  . jav a 2 s  .  c o m*/
 */
public PropertyFormatter getNumberFormat(Object defaultValueWhenEmpty) {
    NumberFormat numberFormat = NumberFormat.getNumberInstance(MainApplication.getInstance().getLocale());
    return new JDKBridgePropertyFormatter(numberFormat, defaultValueWhenEmpty);
}

From source file:com.ethercamp.harmony.service.PeersService.java

private String getPeerDetails(NodeStatistics nodeStatistics, String country, long maxBlockNumber) {
    final String countryRow = "Country: " + country;

    if (nodeStatistics == null || nodeStatistics.getClientId() == null) {
        return countryRow;
    }//w  w  w. j a  va2  s.  c  o m

    final String delimiter = "\n";
    final String blockNumber = "Block number: #"
            + NumberFormat.getNumberInstance(Locale.US).format(maxBlockNumber);
    final String clientId = StringUtils.trimWhitespace(nodeStatistics.getClientId());
    final String details = "Details: " + clientId;
    final String supports = "Supported protocols: " + nodeStatistics.capabilities.stream()
            .filter(c -> c != null).map(c -> StringUtils.capitalize(c.getName()) + ": " + c.getVersion())
            .collect(joining(", "));

    final String[] array = clientId.split("/");
    if (array.length >= 4) {
        final String type = "Type: " + array[0];
        final String os = "OS: " + StringUtils.capitalize(array[2]);
        final String version = "Version: " + array[3];

        return String.join(delimiter, type, os, version, countryRow, "", details, supports, blockNumber);
    } else {
        return String.join(delimiter, countryRow, details, supports, blockNumber);
    }
}