Example usage for java.text DecimalFormat getDecimalFormatSymbols

List of usage examples for java.text DecimalFormat getDecimalFormatSymbols

Introduction

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

Prototype

public DecimalFormatSymbols getDecimalFormatSymbols() 

Source Link

Document

Returns a copy of the decimal format symbols, which is generally not changed by the programmer or user.

Usage

From source file:org.sdr.webrec.core.WebRec.java

public void run() {

    initParameters();//from w  ww .java  2s  . c o m

    String transactionName = "";
    HttpResponse response = null;

    DecimalFormat formatter = new DecimalFormat("#####0.00");
    DecimalFormatSymbols dfs = formatter.getDecimalFormatSymbols();
    formatter.setMinimumFractionDigits(3);
    formatter.setMaximumFractionDigits(3);

    // make sure delimeter is a '.' instead of locale default ','
    dfs.setDecimalSeparator('.');
    formatter.setDecimalFormatSymbols(dfs);

    do {
        t1 = System.currentTimeMillis();
        URL siteURL = null;
        try {

            for (int i = 0; i < url.length; i++) {

                LOGGER.debug("url:" + ((Transaction) url[i]).getUrl());

                Transaction transaction = (Transaction) url[i];
                siteURL = new URL(transaction.getUrl());
                transactionName = transaction.getName();

                //if transaction requires server authentication
                if (transaction.isAutenticate())
                    httpclient.getCredentialsProvider().setCredentials(
                            new AuthScope(siteURL.getHost(), siteURL.getPort()),
                            new UsernamePasswordCredentials(transaction.getWorkload().getUsername(),
                                    transaction.getWorkload().getPassword()));

                // Get HTTP GET method
                httpget = new HttpGet(((Transaction) url[i]).getUrl());

                double startTime = System.nanoTime();

                double endTime = 0.00d;

                response = null;

                // Execute HTTP GET
                try {
                    response = httpclient.execute(httpget);
                    endTime = System.nanoTime();

                } catch (Exception e) {
                    httpget.abort();
                    LOGGER.error("ERROR in receiving response:" + e.getLocalizedMessage());
                    e.printStackTrace();
                }

                double timeLapse = 0;

                if (response != null) {
                    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {

                        timeLapse = endTime - startTime;

                        LOGGER.debug("starttime:" + (new Double(startTime)).toString());
                        LOGGER.debug("timeLapse:" + endTime);
                        LOGGER.debug("timeLapse:" + timeLapse);

                        //move nanos to millis
                        timeLapse = timeLapse / 1000000L;
                        LOGGER.debug("response time:" + formatter.format(timeLapse) + "ms.");
                        out.write(System.currentTimeMillis() / 1000 + ":");
                        out.write(
                                threadName + '.' + transactionName + ":" + formatter.format(timeLapse) + "\n");

                        //content must be consumed just because 
                        //otherwice apache httpconnectionmanager does not release connection back to pool
                        HttpEntity entity = response.getEntity();
                        if (entity != null) {
                            EntityUtils.toByteArray(entity);
                        }

                    } else {
                        LOGGER.error("Status code of transaction:" + transactionName + " was not "
                                + HttpURLConnection.HTTP_OK + " but "
                                + response.getStatusLine().getStatusCode());
                    }

                }
                int sleepTime = delay;
                try {
                    LOGGER.debug("Sleeping " + delay / 1000 + "s...");
                    sleep(sleepTime);
                } catch (InterruptedException ie) {
                    LOGGER.error("ERROR:" + ie);
                    ie.printStackTrace();
                }
            }
        } catch (Exception e) {
            LOGGER.error("Error in thread " + threadName + " with url:" + siteURL + " " + e.getMessage());
            e.printStackTrace();
        }
        try {
            out.flush();
            t2 = System.currentTimeMillis();
            tTask = t2 - t1;

            LOGGER.debug("Total time consumed:" + tTask / 1000 + "s.");

            if (tTask <= interval) {
                //when task takes less than preset time
                LOGGER.debug("Sleeping interval:" + (interval - tTask) / 1000 + "s.");
                sleep(interval - tTask);
            }

            cm.closeExpiredConnections();
        } catch (InterruptedException ie) {
            LOGGER.error("Error:" + ie);
            ie.printStackTrace();
        } catch (Exception e) {
            LOGGER.error("Error:" + e);
            e.printStackTrace();
        }
    } while (true);
}

From source file:com.physphil.android.unitconverterultimate.fragments.ConversionFragment.java

/**
 * Get DecimalFormat used to format result
 *
 * @return DecimalFormat// w  ww .j a va 2  s. co m
 */
private DecimalFormat getDecimalFormat() {
    DecimalFormat formatter = new DecimalFormat();

    //Set maximum number of decimal places
    formatter.setMaximumFractionDigits(mPrefs.getNumberDecimals());

    //Set group and decimal separators
    DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
    symbols.setDecimalSeparator(mPrefs.getDecimalSeparator().charAt(0));

    String groupSeparator = mPrefs.getGroupSeparator();
    boolean isSeparatorUsed = !groupSeparator.equals(getString(R.string.group_separator_none));
    formatter.setGroupingUsed(isSeparatorUsed);
    if (isSeparatorUsed) {
        symbols.setGroupingSeparator(groupSeparator.charAt(0));
    }

    formatter.setDecimalFormatSymbols(symbols);
    return formatter;
}

From source file:org.apache.cordova.core.Globalization.java

private JSONObject getNumberPattern(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();
    try {/*w  w w .  j a  va  2s . co  m*/
        //uses java.text.DecimalFormat to format value
        DecimalFormat fmt = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); //default format
        String symbol = String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator());
        //get Date value + options (if available)
        if (options.getJSONObject(0).length() > 0) {
            //options were included
            if (!((JSONObject) options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)) {
                String fmtOpt = (String) ((JSONObject) options.getJSONObject(0).get(OPTIONS)).get(TYPE);
                if (fmtOpt.equalsIgnoreCase(CURRENCY)) {
                    fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault());
                    symbol = fmt.getDecimalFormatSymbols().getCurrencySymbol();
                } else if (fmtOpt.equalsIgnoreCase(PERCENT)) {
                    fmt = (DecimalFormat) DecimalFormat.getPercentInstance(Locale.getDefault());
                    symbol = String.valueOf(fmt.getDecimalFormatSymbols().getPercent());
                }
            }
        }

        //return properties
        obj.put("pattern", fmt.toPattern());
        obj.put("symbol", symbol);
        obj.put("fraction", fmt.getMinimumFractionDigits());
        obj.put("rounding", new Integer(0));
        obj.put("positive", fmt.getPositivePrefix());
        obj.put("negative", fmt.getNegativePrefix());
        obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator()));
        obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator()));

        return obj;
    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}

From source file:com.brq.wallet.external.cashila.activity.CashilaNewFragment.java

private BigDecimal getAmount() {
    DecimalFormat numberFormat = (DecimalFormat) DecimalFormat.getNumberInstance(mbw.getLocale());
    BigDecimal amount;/* w ww  . j  a v  a2  s . c o  m*/

    try {
        String amountText = etAmount.getText().toString();
        if (Strings.isNullOrEmpty(amountText)) {
            return null;
        }

        char decimalSeparator = numberFormat.getDecimalFormatSymbols().getDecimalSeparator();

        // the num entry on (some?) android defaults to "." as decimal separator, no matter
        // what locale the user has chosen
        if (decimalSeparator == '.') {
            amountText = amountText.replace(',', decimalSeparator);
        } else {
            amountText = amountText.replace('.', decimalSeparator);
        }

        amount = new BigDecimal(numberFormat.parse(amountText).doubleValue());
    } catch (ParseException e) {
        new Toaster(getActivity()).toast(getResources().getString(R.string.cashila_amount_not_valid), true);
        return null;
    }
    return amount;
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();/* ww  w .  j  a  v a2  s .c  om*/
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        BigDecimal number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final NumberFormatter numberFormatter = new NumberFormatter();
            final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
            number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue()));
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.decimal.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid decimal value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:org.mifosplatform.infrastructure.core.serialization.JsonParserHelper.java

public Integer convertToInteger(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();/*w  w  w  .  ja va 2s .co m*/
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        Integer number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            df.setParseBigDecimal(true);

            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final Number parsedNumber = df.parse(source);

            final double parsedNumberDouble = parsedNumber.doubleValue();
            final int parsedNumberInteger = parsedNumber.intValue();

            if (source.contains(Character.toString(symbols.getDecimalSeparator()))) {
                throw new ParseException(source, 0);
            }

            if (!Double.valueOf(parsedNumberDouble)
                    .equals(Double.valueOf(Integer.valueOf(parsedNumberInteger)))) {
                throw new ParseException(source, 0);
            }

            number = parsedNumber.intValue();
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<ApiParameterError>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.integer.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid integer value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}

From source file:org.apache.cordova.globalization.Globalization.java

private JSONObject getNumberPattern(JSONArray options) throws GlobalizationError {
    JSONObject obj = new JSONObject();
    try {//w  w  w.  j  a v a 2 s  . c om
        //uses java.text.DecimalFormat to format value
        DecimalFormat fmt = (DecimalFormat) DecimalFormat.getInstance(Locale.getDefault()); //default format
        String symbol = String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator());
        //get Date value + options (if available)
        if (options.getJSONObject(0).length() > 0) {
            //options were included
            if (!((JSONObject) options.getJSONObject(0).get(OPTIONS)).isNull(TYPE)) {
                String fmtOpt = (String) ((JSONObject) options.getJSONObject(0).get(OPTIONS)).get(TYPE);
                if (fmtOpt.equalsIgnoreCase(CURRENCY)) {
                    fmt = (DecimalFormat) DecimalFormat.getCurrencyInstance(Locale.getDefault());
                    symbol = fmt.getDecimalFormatSymbols().getCurrencySymbol();
                } else if (fmtOpt.equalsIgnoreCase(PERCENT)) {
                    fmt = (DecimalFormat) DecimalFormat.getPercentInstance(Locale.getDefault());
                    symbol = String.valueOf(fmt.getDecimalFormatSymbols().getPercent());
                }
            }
        }

        //return properties
        obj.put("pattern", fmt.toPattern());
        obj.put("symbol", symbol);
        obj.put("fraction", fmt.getMinimumFractionDigits());
        obj.put("rounding", Integer.valueOf(0));
        obj.put("positive", fmt.getPositivePrefix());
        obj.put("negative", fmt.getNegativePrefix());
        obj.put("decimal", String.valueOf(fmt.getDecimalFormatSymbols().getDecimalSeparator()));
        obj.put("grouping", String.valueOf(fmt.getDecimalFormatSymbols().getGroupingSeparator()));

        return obj;
    } catch (Exception ge) {
        throw new GlobalizationError(GlobalizationError.PATTERN_ERROR);
    }
}

From source file:org.pentaho.di.trans.steps.datagrid.DataGridMeta.java

public void setDefault() {
    int i, nrfields = 0;

    allocate(nrfields);/*from   ww  w .jav a  2  s .  co  m*/

    DecimalFormat decimalFormat = new DecimalFormat();

    for (i = 0; i < nrfields; i++) {
        fieldName[i] = "field" + i;
        fieldType[i] = "Number";
        fieldFormat[i] = "\u00A40,000,000.00;\u00A4-0,000,000.00";
        fieldLength[i] = 9;
        fieldPrecision[i] = 2;
        currency[i] = decimalFormat.getDecimalFormatSymbols().getCurrencySymbol();
        decimal[i] = new String(new char[] { decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() });
        group[i] = new String(new char[] { decimalFormat.getDecimalFormatSymbols().getGroupingSeparator() });
        setEmptyString[i] = false;
    }

    dataLines = new ArrayList<List<String>>();
}

From source file:org.pentaho.di.trans.steps.rowgenerator.RowGeneratorMeta.java

public void setDefault() {
    int i, nrfields = 0;

    allocate(nrfields);/*from   w w  w.j  a  v a2 s  .c o  m*/

    DecimalFormat decimalFormat = new DecimalFormat();

    for (i = 0; i < nrfields; i++) {
        fieldName[i] = "field" + i;
        fieldType[i] = "Number";
        fieldFormat[i] = "\u00A40,000,000.00;\u00A4-0,000,000.00";
        fieldLength[i] = 9;
        fieldPrecision[i] = 2;
        currency[i] = decimalFormat.getDecimalFormatSymbols().getCurrencySymbol();
        decimal[i] = new String(new char[] { decimalFormat.getDecimalFormatSymbols().getDecimalSeparator() });
        group[i] = new String(new char[] { decimalFormat.getDecimalFormatSymbols().getGroupingSeparator() });
        value[i] = "-";
        setEmptyString[i] = false;
    }

    rowLimit = "10";
}

From source file:com.gst.infrastructure.core.serialization.JsonParserHelper.java

public BigDecimal convertFrom(final String numericalValueFormatted, final String parameterName,
        final Locale clientApplicationLocale) {

    if (clientApplicationLocale == null) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final String defaultMessage = new StringBuilder(
                "The parameter '" + parameterName + "' requires a 'locale' parameter to be passed with it.")
                        .toString();// ww  w .j  a v  a2 s. c  o m
        final ApiParameterError error = ApiParameterError
                .parameterError("validation.msg.missing.locale.parameter", defaultMessage, parameterName);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }

    try {
        BigDecimal number = null;

        if (StringUtils.isNotBlank(numericalValueFormatted)) {

            String source = numericalValueFormatted.trim();

            final NumberFormat format = NumberFormat.getNumberInstance(clientApplicationLocale);
            final DecimalFormat df = (DecimalFormat) format;
            final DecimalFormatSymbols symbols = df.getDecimalFormatSymbols();
            // http://bugs.sun.com/view_bug.do?bug_id=4510618
            final char groupingSeparator = symbols.getGroupingSeparator();
            if (groupingSeparator == '\u00a0') {
                source = source.replaceAll(" ", Character.toString('\u00a0'));
            }

            final NumberFormatter numberFormatter = new NumberFormatter();
            final Number parsedNumber = numberFormatter.parse(source, clientApplicationLocale);
            if (parsedNumber instanceof BigDecimal) {
                number = (BigDecimal) parsedNumber;
            } else {
                number = BigDecimal.valueOf(Double.valueOf(parsedNumber.doubleValue()));
            }
        }

        return number;
    } catch (final ParseException e) {

        final List<ApiParameterError> dataValidationErrors = new ArrayList<>();
        final ApiParameterError error = ApiParameterError.parameterError(
                "validation.msg.invalid.decimal.format",
                "The parameter " + parameterName + " has value: " + numericalValueFormatted
                        + " which is invalid decimal value for provided locale of ["
                        + clientApplicationLocale.toString() + "].",
                parameterName, numericalValueFormatted, clientApplicationLocale);
        error.setValue(numericalValueFormatted);
        dataValidationErrors.add(error);

        throw new PlatformApiDataValidationException("validation.msg.validation.errors.exist",
                "Validation errors exist.", dataValidationErrors);
    }
}