Example usage for java.text DecimalFormat applyPattern

List of usage examples for java.text DecimalFormat applyPattern

Introduction

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

Prototype

public void applyPattern(String pattern) 

Source Link

Document

Apply the given pattern to this Format object.

Usage

From source file:name.gumartinm.weather.information.widget.WidgetIntentService.java

private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation,
        final int appWidgetId) {

    // 1. Update units of measurement.

    UnitsConversor tempUnitsConversor;//from w w  w  . j  a va2s.  com
    String keyPreference = this.getApplicationContext()
            .getString(R.string.widget_preferences_temperature_units_key);
    String realKeyPreference = keyPreference + "_" + appWidgetId;
    // What was saved to permanent storage (or default values if it is the first time)
    final int tempValue = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(realKeyPreference, 0);
    final String tempSymbol = this.getResources()
            .getStringArray(R.array.weather_preferences_temperature)[tempValue];
    if (tempValue == 0) {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return value - 273.15;
            }

        };
    } else if (tempValue == 1) {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return (value * 1.8) - 459.67;
            }

        };
    } else {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return value;
            }

        };
    }

    // 2. Update country.
    keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_country_switch_key);
    realKeyPreference = keyPreference + "_" + appWidgetId;
    // What was saved to permanent storage (or default values if it is the first time)
    final boolean isCountry = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getBoolean(realKeyPreference, false);

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

    // 4. Prepare data for RemoteViews.
    String tempMax = "";
    if (current.getMain().getTemp_max() != null) {
        double conversion = (Double) current.getMain().getTemp_max();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = tempFormatter.format(conversion) + tempSymbol;
    }
    String tempMin = "";
    if (current.getMain().getTemp_min() != null) {
        double conversion = (Double) current.getMain().getTemp_min();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = tempFormatter.format(conversion) + tempSymbol;
    }
    Bitmap picture;
    if ((current.getWeather().size() > 0) && (current.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
        final String icon = current.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }
    final String city = weatherLocation.getCity();
    final String country = weatherLocation.getCountry();

    // 5. Insert data in RemoteViews.
    final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(),
            R.layout.appwidget);
    remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture);
    remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax);
    remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin);
    remoteView.setTextViewText(R.id.weather_appwidget_city, city);
    if (!isCountry) {
        remoteView.setViewVisibility(R.id.weather_appwidget_country, View.GONE);
    } else {
        // TODO: It is as if Android had a view cache. If I did not set VISIBLE value,
        // the country field would be gone forever... :/
        remoteView.setViewVisibility(R.id.weather_appwidget_country, View.VISIBLE);
        remoteView.setTextViewText(R.id.weather_appwidget_country, country);
    }

    // 6. Activity launcher.
    final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
    resultIntent.putExtra("actionFromUser", true);
    resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
    final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/"), String.valueOf(appWidgetId));
    resultIntent.setData(data);

    final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(WidgetConfigure.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);

    return remoteView;
}

From source file:com.intuit.karate.cucumber.KarateJunitFormatter.java

private String formatTime(double time) {
    DecimalFormat nfmt = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    nfmt.applyPattern("0.######");
    return nfmt.format(time);
}

From source file:org.enerj.apache.commons.beanutils.locale.converters.DecimalLocaleConverter.java

/**
 * Convert the specified locale-sensitive input object into an output object of the
 * specified type.//w  w w . j av a 2s  . co m
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 *
 * @exception ConversionException if conversion cannot be performed
 *  successfully
 */
protected Object parse(Object value, String pattern) throws ParseException {
    // DecimalFormat is not thread safe so best to construct one each time
    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);
    // if some constructors default pattern to null, it makes only sense to handle null pattern gracefully
    if (pattern != null) {
        if (locPattern) {
            formatter.applyLocalizedPattern(pattern);
        } else {
            formatter.applyPattern(pattern);
        }
    } else {
        log.warn("No pattern provided, using default.");
    }

    return formatter.parse((String) value);
}

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

/**
 * Convert the specified locale-sensitive input object into an output 
 * object of the specified type./*w w w .j a v a2  s  . c om*/
 *
 * @param value The input object to be converted
 * @param pattern The pattern is used for the convertion
 * @return The converted value
 *
 * @exception org.apache.commons.beanutils.ConversionException if conversion
 * cannot be performed successfully
 * @throws ParseException if an error occurs parsing a String to a Number
 */
protected Object parse(Object value, String pattern) throws ParseException {

    if (value instanceof Number) {
        return value;
    }

    // Note that despite the ambiguous "getInstance" name, and despite the
    // fact that objects returned from this method have the same toString
    // representation, each call to getInstance actually returns a new
    // object.
    DecimalFormat formatter = (DecimalFormat) DecimalFormat.getInstance(locale);

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

    return formatter.parse((String) value);
}

From source file:org.jbpm.formModeler.core.processing.fieldHandlers.NumericFieldHandler.java

public Object getTheValue(Field field, String[] paramValue, String desiredClassName) throws Exception {
    if (paramValue == null || paramValue.length == 0)
        return null;

    if (desiredClassName.equals("byte")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Byte((byte) 0);
        else/*w  ww. j  a v a 2  s .  c o  m*/
            return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals("short")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Short((short) 0);
        else
            return Short.decode(paramValue[0]);
    } else if (desiredClassName.equals("int")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Integer(0);
        else
            return Integer.decode(paramValue[0]);
    } else if (desiredClassName.equals("long")) {
        if (StringUtils.isEmpty(paramValue[0]))
            return new Long(0L);
        else
            return Long.decode(paramValue[0]);
    } else if (desiredClassName.equals(Byte.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Byte.decode(paramValue[0]);
    } else if (desiredClassName.equals(Short.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Short.decode(paramValue[0]);

    } else if (desiredClassName.equals(Integer.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Integer.decode(paramValue[0]);

    } else if (desiredClassName.equals(Long.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return Long.decode(paramValue[0]);

    } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")
            || desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")
            || desiredClassName.equals(BigDecimal.class.getName())) {

        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();

        DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(new Locale(LocaleManager.currentLang()));
        if (desiredClassName.equals(BigDecimal.class.getName()))
            df.setParseBigDecimal(true);
        String pattern = getFieldPattern(field);
        if (pattern != null && !"".equals(pattern)) {
            df.applyPattern(pattern);
        } else {
            df.applyPattern("###.##");
        }
        ParsePosition pp = new ParsePosition(0);
        Number num = df.parse(paramValue[0], pp);
        if (paramValue[0].length() != pp.getIndex() || num == null) {
            log.debug("Error on parsing value");
            throw new ParseException("Error parsing value", pp.getIndex());
        }

        if (desiredClassName.equals(BigDecimal.class.getName())) {
            return num;
        } else if (desiredClassName.equals(Float.class.getName()) || desiredClassName.equals("float")) {
            return new Float(num.floatValue());
        } else if (desiredClassName.equals(Double.class.getName()) || desiredClassName.equals("double")) {
            return new Double(num.doubleValue());
        }
    } else if (desiredClassName.equals(BigInteger.class.getName())) {
        if (StringUtils.isEmpty(paramValue[0]))
            throw new EmptyNumberException();
        return new BigInteger(paramValue[0]);

    }
    throw new IllegalArgumentException("Invalid class for NumericFieldHandler: " + desiredClassName);
}

From source file:org.enerj.apache.commons.beanutils.locale.converters.StringLocaleConverter.java

/**
 * Make an instance of DecimalFormat.//from ww  w  .ja  v  a2s  .c  o m
 *
 * @param locale The locale
 * @param pattern The pattern is used for the convertion
 *
 * @exception ConversionException if conversion cannot be performed
 *  successfully
 */
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.warn("No pattern provided, using default.");
    }

    return numberFormat;
}

From source file:com.joliciel.jochre.stats.FScoreCalculator.java

public void writeScoresToCSV(Writer fscoreFileWriter) {
    try {/*  w  w w  . j  av a  2  s  .  c  om*/
        Set<E> outcomeSet = new TreeSet<E>();
        outcomeSet.addAll(this.getOutcomeSet());
        fscoreFileWriter.write(CSV.format("outcome"));
        for (E outcome : outcomeSet) {
            fscoreFileWriter.write(CSV.format(outcome.toString()));
        }
        fscoreFileWriter.write(CSV.format("true+") + CSV.format("false+") + CSV.format("false-")
                + CSV.format("precision") + CSV.format("recall") + CSV.format("f-score"));
        fscoreFileWriter.write("\n");

        DecimalFormat df = (DecimalFormat) DecimalFormat.getNumberInstance(Locale.US);
        df.applyPattern("#.##");

        double totalPrecisionSum = 0;
        double totalRecallSum = 0;
        double totalFscoreSum = 0;
        for (E outcome : outcomeSet) {
            fscoreFileWriter.write(CSV.format(outcome.toString()));
            for (E outcome2 : outcomeSet) {
                int falseNegativeCount = 0;
                Map<E, Integer> falseNegatives = this.getFalseNegatives(outcome);
                if (falseNegatives != null && falseNegatives.containsKey(outcome2)) {
                    falseNegativeCount = this.getFalseNegatives(outcome).get(outcome2);
                }
                fscoreFileWriter.write(CSV.format(falseNegativeCount));
            }
            fscoreFileWriter.write(CSV.format(this.getTruePositiveCount(outcome)));
            fscoreFileWriter.write(CSV.format(this.getFalsePositiveCount(outcome)));
            fscoreFileWriter.write(CSV.format(this.getFalseNegativeCount(outcome)));
            fscoreFileWriter.write(CSV.format(this.getPrecision(outcome) * 100));
            fscoreFileWriter.write(CSV.format(this.getRecall(outcome) * 100));
            fscoreFileWriter.write(CSV.format(this.getFScore(outcome) * 100));
            fscoreFileWriter.write("\n");

            totalPrecisionSum += this.getPrecision(outcome);
            totalRecallSum += this.getRecall(outcome);
            totalFscoreSum += this.getFScore(outcome);
        }

        fscoreFileWriter.write(CSV.format("TOTAL"));
        for (E outcome : outcomeSet) {
            outcome.hashCode();
            fscoreFileWriter.write(CSV.getCsvSeparator());
        }
        fscoreFileWriter.write(CSV.format(this.getTotalTruePositiveCount()));
        fscoreFileWriter.write(CSV.format(this.getTotalFalsePositiveCount()));
        fscoreFileWriter.write(CSV.format(this.getTotalFalseNegativeCount()));
        fscoreFileWriter.write(CSV.format(this.getTotalPrecision() * 100));
        fscoreFileWriter.write(CSV.format(this.getTotalRecall() * 100));
        fscoreFileWriter.write(CSV.format(this.getTotalFScore() * 100));
        fscoreFileWriter.write("\n");

        fscoreFileWriter.write(CSV.format("AVERAGE"));
        for (E outcome : outcomeSet) {
            outcome.hashCode();
            fscoreFileWriter.write(CSV.getCsvSeparator());
        }
        fscoreFileWriter.write(CSV.getCsvSeparator());
        fscoreFileWriter.write(CSV.getCsvSeparator());
        fscoreFileWriter.write(CSV.getCsvSeparator());
        fscoreFileWriter.write(CSV.format((totalPrecisionSum / outcomeSet.size()) * 100));
        fscoreFileWriter.write(CSV.format((totalRecallSum / outcomeSet.size()) * 100));
        fscoreFileWriter.write(CSV.format((totalFscoreSum / outcomeSet.size()) * 100));
        fscoreFileWriter.write("\n");
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

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

/**
 * Make an instance of DecimalFormat./*from   w  w  w. ja v a 2 s . c  om*/
 *
 * @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.joliciel.csvLearner.utils.FScoreCalculator.java

public void writeScoresToCSV(Writer fscoreFileWriter) {
    try {/*  w  ww .  j a v  a  2  s. c  om*/
        Set<E> outcomeSet = new TreeSet<E>();
        outcomeSet.addAll(this.getOutcomeSet());
        fscoreFileWriter.write("outcome,");
        for (E outcome : outcomeSet) {
            fscoreFileWriter.write(outcome.toString() + ",");
        }
        fscoreFileWriter.write("true+,false+,false-,precision,recall,f-score");
        fscoreFileWriter.write("\n");

        DecimalFormat df = (DecimalFormat) DecimalFormat.getNumberInstance(Locale.US);
        df.applyPattern("#.##");

        double totalPrecisionSum = 0;
        double totalRecallSum = 0;
        double totalFscoreSum = 0;
        for (E outcome : outcomeSet) {
            fscoreFileWriter.write(outcome.toString() + ",");
            for (E outcome2 : outcomeSet) {
                int falseNegativeCount = 0;
                Map<E, Integer> falseNegatives = this.getFalseNegatives(outcome);
                if (falseNegatives != null && falseNegatives.containsKey(outcome2)) {
                    falseNegativeCount = this.getFalseNegatives(outcome).get(outcome2);
                }
                fscoreFileWriter.write(falseNegativeCount + ",");
            }
            fscoreFileWriter.write(df.format(this.getTruePositiveCount(outcome)) + ",");
            fscoreFileWriter.write(df.format(this.getFalsePositiveCount(outcome)) + ",");
            fscoreFileWriter.write(df.format(this.getFalseNegativeCount(outcome)) + ",");
            fscoreFileWriter.write(df.format(this.getPrecision(outcome) * 100) + ",");
            fscoreFileWriter.write(df.format(this.getRecall(outcome) * 100) + ",");
            fscoreFileWriter.write(df.format(this.getFScore(outcome) * 100) + ",");
            fscoreFileWriter.write("\n");

            totalPrecisionSum += this.getPrecision(outcome);
            totalRecallSum += this.getRecall(outcome);
            totalFscoreSum += this.getFScore(outcome);
        }

        fscoreFileWriter.write("TOTAL,");
        for (E outcome : outcomeSet) {
            outcome.hashCode();
            fscoreFileWriter.write(",");
        }
        fscoreFileWriter.write(df.format(this.getTotalTruePositiveCount()) + ",");
        fscoreFileWriter.write(df.format(this.getTotalFalsePositiveCount()) + ",");
        fscoreFileWriter.write(df.format(this.getTotalFalseNegativeCount()) + ",");
        fscoreFileWriter.write(df.format(this.getTotalPrecision() * 100) + ",");
        fscoreFileWriter.write(df.format(this.getTotalRecall() * 100) + ",");
        fscoreFileWriter.write(df.format(this.getTotalFScore() * 100) + ",");
        fscoreFileWriter.write("\n");

        fscoreFileWriter.write("AVERAGE,");
        for (E outcome : outcomeSet) {
            outcome.hashCode();
            fscoreFileWriter.write(",");
        }
        fscoreFileWriter.write(",");
        fscoreFileWriter.write(",");
        fscoreFileWriter.write(",");
        fscoreFileWriter.write(df.format((totalPrecisionSum / outcomeSet.size()) * 100) + ",");
        fscoreFileWriter.write(df.format((totalRecallSum / outcomeSet.size()) * 100) + ",");
        fscoreFileWriter.write(df.format((totalFscoreSum / outcomeSet.size()) * 100) + ",");
        fscoreFileWriter.write("\n");
        fscoreFileWriter.write("\n");
    } catch (IOException ioe) {
        throw new RuntimeException(ioe);
    }
}

From source file:alignment.BinaryToCSV.java

/**
 * /* ww  w .  j  a  v a2 s .  co  m*/
 *
 * @param 
 * @return 
 */
public int readHeader() {
    byte[] buffer = new byte[HEADER_SIZE]; //178
    int nRead = 0;

    try {
        if ((nRead = inputStream.read(buffer)) == -1)
            System.err.println("Header read failed");
    } catch (IOException e) {
        e.printStackTrace();
    }
    counter += nRead;

    byteToBits(buffer[0], 0);
    LN = b7;
    System.out.println("Low Noise: " + LN);
    gyro = b6;
    System.out.println("Gyroscope: " + gyro);
    mag = b5;
    System.out.println("Magnetometer: " + mag);

    byteToBits(buffer[1], 1);
    WR = b4;
    System.out.println("Wide Range: " + WR);

    byteToBits(buffer[10], 10);
    sync = b2;
    System.out.println("Sync: " + sync);
    master = b1;
    System.out.println("Master: " + master);

    NumberFormat nf = NumberFormat.getNumberInstance(Locale.ENGLISH);
    DecimalFormat df = (DecimalFormat) nf;
    df.applyPattern("#.#");
    sampleRate = Double.parseDouble(
            df.format(TWO_EXP_15 / (double) ((int) (buffer[21] & 0xFF) + ((int) (buffer[20] & 0xFF) << 8))));
    System.out.println("SampleRate: " + sampleRate);

    byte[] tempBytes = new byte[4];
    tempBytes[3] = buffer[174];
    tempBytes[2] = buffer[175];
    tempBytes[1] = buffer[176];
    tempBytes[0] = buffer[177];

    ByteBuffer bb = ByteBuffer.wrap(tempBytes);
    initialTS32 = bb.getInt();
    System.out.println("Initial Timestamp: " + initialTS32);

    for (int i = 0; i < buffer.length; i++) {
        //byteToBits(buffer[i], i);
    }
    return nRead;
}