Example usage for java.text DecimalFormat setDecimalFormatSymbols

List of usage examples for java.text DecimalFormat setDecimalFormatSymbols

Introduction

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

Prototype

public void setDecimalFormatSymbols(DecimalFormatSymbols newSymbols) 

Source Link

Document

Sets the decimal format symbols, which is generally not changed by the programmer or user.

Usage

From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java

/**
 * Writes out the matrix in row major (packed) order. No labels are outputed.
 *
 * @param jobConf/*from  w w w  . j  a v a 2  s. c o m*/
 * @param input
 * @param output
 * @param digits
 * @throws IOException
 */
public static void printRowMajorMatrix(JobConf jobConf, String input, String output, int digits)
        throws IOException {
    JobConf conf = new JobConf(jobConf, CalculateCosineDistanceMatrix.class);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(digits);
    //format.setMinimumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);

    final Path inputPath = new Path(input);
    final FileSystem fs = inputPath.getFileSystem(conf);
    final Path qInputPath = fs.makeQualified(inputPath);
    final Path outputPath = new Path(output);
    Path[] paths = FileUtils.ls(conf, qInputPath.toString() + Path.SEPARATOR + "part-*");

    FSDataOutputStream fos = fs.create(outputPath, true); // throws nothing!
    final Writer writer = new OutputStreamWriter(fos);
    final Text key = new Text();
    final DenseVectorWritable value = new DenseVectorWritable();
    for (int idx = 0; idx < paths.length; idx++) {
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, paths[idx], conf);
        boolean hasNext = reader.next(key, value);
        while (hasNext) {

            final DenseVector vector = value.get();
            final StringBuilder sb = new StringBuilder();
            for (int i = 0; i < vector.getCardinality(); i++) {
                final String s = format.format(vector.get(i)); // format the number
                sb.append(s);
                sb.append(' ');
            }
            writer.write(sb.toString());
            hasNext = reader.next(key, value);
        }
        try {
            writer.flush();
            reader.close();
        } catch (IOException ioe) {
            // closing the SequenceFile.Reader will throw an exception if the file is over some unknown size
            LOG.debug("Probably caused by closing the SequenceFile.Reader. All is well", ioe);
        }
    }
    try {
        writer.close();
        fos.flush();
        fos.close();
    } catch (IOException ioe) {
        LOG.debug("Caused by distributed cache output stream.", ioe);
    }
}

From source file:org.mitre.ccv.mapred.CalculateCosineDistanceMatrix.java

/**
 * Outputs the distance matrix (DenseVectors) in Phylip Square format. Names/labels are limited to 10-characters!
 *
 * @param jobConf/*from   w  ww .  j  a  va  2  s.c om*/
 * @param input             input directory name containing DenseVectors (as generated by this class).
 * @param output            output file name
 * @param fractionDigits    number of digits after decimal point
 * @throws IOException
 */
public static void printPhylipSquare(JobConf jobConf, String input, String output, int fractionDigits)
        throws IOException {
    JobConf conf = new JobConf(jobConf, CalculateCosineDistanceMatrix.class);

    DecimalFormat format = new DecimalFormat();
    format.setDecimalFormatSymbols(new DecimalFormatSymbols(Locale.US));
    format.setMinimumIntegerDigits(1);
    format.setMaximumFractionDigits(fractionDigits);
    //format.setMinimumFractionDigits(fractionDigits);
    format.setGroupingUsed(false);

    final Path inputPath = new Path(input);
    final FileSystem fs = inputPath.getFileSystem(conf);
    final Path qInputPath = fs.makeQualified(inputPath);
    final Path outputPath = new Path(output);
    Path[] paths = FileUtils.ls(conf, qInputPath.toString() + Path.SEPARATOR + "part-*");

    FSDataOutputStream fos = fs.create(outputPath, true); // throws nothing!
    Writer writer = new OutputStreamWriter(fos);
    Text key = new Text();
    DenseVectorWritable value = new DenseVectorWritable();
    Boolean wroteHeader = false;
    for (int idx = 0; idx < paths.length; idx++) {
        SequenceFile.Reader reader = new SequenceFile.Reader(fs, paths[idx], conf);
        boolean hasNext = reader.next(key, value);
        while (hasNext) {

            final DenseVector vector = value.get();
            if (!wroteHeader) {
                writer.write(String.format("\t%d\n", vector.getCardinality()));
                wroteHeader = true;
            }

            final StringBuilder sb = new StringBuilder();
            final String name = key.toString();
            sb.append(name.substring(0, (name.length() > 10 ? 10 : name.length())));
            final int padding = Math.max(1, 10 - name.length());
            for (int k = 0; k < padding; k++) {
                sb.append(' ');
            }
            sb.append(' ');
            for (int i = 0; i < vector.getCardinality(); i++) {
                final String s = format.format(vector.get(i)); // format the number
                sb.append(s);
                sb.append(' ');
            }
            sb.append("\n");
            writer.write(sb.toString());
            hasNext = reader.next(key, value);
        }
        try {
            writer.flush();
            reader.close();
        } catch (IOException ioe) {
            // closing the SequenceFile.Reader will throw an exception if the file is over some unknown size
            LOG.debug("Probably caused by closing the SequenceFile.Reader. All is well", ioe);
        }
    }
    try {
        writer.close();
        fos.flush();
        fos.close();
    } catch (IOException ioe) {
        LOG.debug("Caused by distributed cache output stream.", ioe);
    }
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * Format {@link String} as a Volume/*from   ww  w. j ava  2  s .  com*/
 *  
 * WARNING: Only use this method to present data to the screen
 * 
 * @param locale {@link Locale}
 * @param stringToFormat  {@link String} to format
 * @return a string formatted as a volume with group separators (eg, 131.224.000) assuming the receiver is an int string read from XML
 */
public static String formatVolume(Locale locale, String stringToFormat) {
    if (stringToFormat == null || stringToFormat.length() == 0) {
        return null;
    }

    String result = null;

    DecimalFormat formatter = new DecimalFormat();
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));

    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
    formatter.setMaximumFractionDigits(0);

    result = formatter.format(Double.parseDouble(stringToFormat));

    return result;
}

From source file:com.itude.mobile.android.util.StringUtil.java

/**
 * Set the formatter./*from   w w  w  . ja v a 2  s  .com*/
 * 
 * @param formatter {@link DecimalFormat}
 * @param locale {@link Locale}
 * @param minimalDecimalNumbers minimal number of decimals
 * @param maximumDecimalNumbers maximum number of decimals
 */
private static void setupFormatter(DecimalFormat formatter, Locale locale, int minimalDecimalNumbers,
        int maximumDecimalNumbers) {
    formatter.setDecimalFormatSymbols(new DecimalFormatSymbols(locale));
    formatter.setMinimumIntegerDigits(1);
    formatter.setMinimumFractionDigits(minimalDecimalNumbers);
    formatter.setMaximumFractionDigits(maximumDecimalNumbers);
    formatter.setGroupingUsed(true);
    formatter.setGroupingSize(3);
}

From source file:org.revager.tools.GUITools.java

/**
 * Formats the given spinner./*  w  w w  .j  av  a2s  .  c  o  m*/
 * 
 * @param sp
 *            the spinner
 */
public static void formatSpinner(JSpinner sp, boolean hideBorder) {
    JSpinner.DefaultEditor defEditor = (JSpinner.DefaultEditor) sp.getEditor();
    JFormattedTextField ftf = defEditor.getTextField();
    ftf.setFocusLostBehavior(JFormattedTextField.COMMIT_OR_REVERT);
    InternationalFormatter intFormatter = (InternationalFormatter) ftf.getFormatter();
    DecimalFormat decimalFormat = (DecimalFormat) intFormatter.getFormat();
    decimalFormat.applyPattern("00");
    DecimalFormatSymbols geSymbols = new DecimalFormatSymbols(Data.getInstance().getLocale());
    decimalFormat.setDecimalFormatSymbols(geSymbols);

    if (hideBorder) {
        sp.setBorder(null);
    }
}

From source file:com.coinblesk.client.utils.UIUtils.java

public static String coinToAmount(Context context, Coin coin) {
    // transform a given coin value to the "amount string".
    BigDecimal coinAmount = new BigDecimal(coin.getValue());
    BigDecimal div = new BigDecimal(Coin.COIN.getValue());

    if (SharedPrefUtils.isBitcoinScaleBTC(context)) {
        div = new BigDecimal(Coin.COIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMilliBTC(context)) {
        div = new BigDecimal(Coin.MILLICOIN.getValue());
    } else if (SharedPrefUtils.isBitcoinScaleMicroBTC(context)) {
        div = new BigDecimal(Coin.MICROCOIN.getValue());
    }/*from  ww  w.  ja va 2  s .com*/

    DecimalFormat df = new DecimalFormat("#.####");
    df.setRoundingMode(RoundingMode.DOWN);
    df.setMaximumFractionDigits(4);
    DecimalFormatSymbols decFormat = new DecimalFormatSymbols();
    decFormat.setDecimalSeparator('.');
    df.setDecimalFormatSymbols(decFormat);
    String amount = df.format(coinAmount.divide(div));
    return amount;
}

From source file:de.langerhans.wallet.ExchangeRatesProvider.java

private static Map<String, ExchangeRate> requestExchangeRates(final URL url, double dogeBtcConversion,
        final String userAgent, final String source, final String... fields) {
    final long start = System.currentTimeMillis();

    HttpURLConnection connection = null;
    Reader reader = null;/*from  ww w.  j  a va 2 s  . c o m*/

    try {
        connection = (HttpURLConnection) url.openConnection();

        connection.setInstanceFollowRedirects(false);
        connection.setConnectTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.setReadTimeout(Constants.HTTP_TIMEOUT_MS);
        connection.addRequestProperty("User-Agent", userAgent);
        connection.addRequestProperty("Accept-Encoding", "gzip");
        connection.connect();

        final int responseCode = connection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            final String contentEncoding = connection.getContentEncoding();

            InputStream is = new BufferedInputStream(connection.getInputStream(), 1024);
            if ("gzip".equalsIgnoreCase(contentEncoding))
                is = new GZIPInputStream(is);

            reader = new InputStreamReader(is, Charsets.UTF_8);
            final StringBuilder content = new StringBuilder();
            final long length = Io.copy(reader, content);

            final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>();

            final JSONObject head = new JSONObject(content.toString());
            for (final Iterator<String> i = head.keys(); i.hasNext();) {
                final String currencyCode = i.next();
                if (!"timestamp".equals(currencyCode)) {
                    final JSONObject o = head.getJSONObject(currencyCode);

                    for (final String field : fields) {
                        final String rate = o.optString(field, null);

                        if (rate != null) {
                            try {
                                final double btcRate = Double
                                        .parseDouble(Fiat.parseFiat(currencyCode, rate).toPlainString());
                                DecimalFormat df = new DecimalFormat("#.########");
                                df.setRoundingMode(RoundingMode.HALF_UP);
                                DecimalFormatSymbols dfs = new DecimalFormatSymbols();
                                dfs.setDecimalSeparator('.');
                                dfs.setGroupingSeparator(',');
                                df.setDecimalFormatSymbols(dfs);
                                final Fiat dogeRate = Fiat.parseFiat(currencyCode,
                                        df.format(btcRate * dogeBtcConversion));

                                if (dogeRate.signum() > 0) {
                                    rates.put(currencyCode, new ExchangeRate(
                                            new com.dogecoin.dogecoinj.utils.ExchangeRate(dogeRate), source));
                                    break;
                                }
                            } catch (final NumberFormatException x) {
                                log.warn("problem fetching {} exchange rate from {} ({}): {}", currencyCode,
                                        url, contentEncoding, x.getMessage());
                            }
                        }
                    }
                }
            }

            log.info("fetched exchange rates from {} ({}), {} chars, took {} ms", url, contentEncoding, length,
                    System.currentTimeMillis() - start);

            return rates;
        } else {
            log.warn("http status {} when fetching exchange rates from {}", responseCode, url);
        }
    } catch (final Exception x) {
        log.warn("problem fetching exchange rates from " + url, x);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (final IOException x) {
                // swallow
            }
        }

        if (connection != null)
            connection.disconnect();
    }

    return null;
}

From source file:com.panet.imeta.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);/*from w ww.j  av  a  2 s  . c  om*/
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new KettleValueException(message);
    }
}

From source file:org.openossad.util.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws OpenDESIGNERValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern))
        df.applyPattern(pattern);/*from  w  w w  .j a  v  a2 s .c  om*/
    if (!Const.isEmpty(decimal))
        dfs.setDecimalSeparator(decimal.charAt(0));
    if (!Const.isEmpty(grouping))
        dfs.setGroupingSeparator(grouping.charAt(0));
    if (!Const.isEmpty(currency))
        dfs.setCurrencySymbol(currency);
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern))
            message += " pattern=" + pattern;
        if (!isEmpty(decimal))
            message += " decimal=" + decimal;
        if (!isEmpty(grouping))
            message += " grouping=" + grouping.charAt(0);
        if (!isEmpty(currency))
            message += " currency=" + currency;
        throw new OpenDESIGNERValueException(message);
    }
}

From source file:org.pentaho.di.core.util.StringUtil.java

public static double str2num(String pattern, String decimal, String grouping, String currency, String value)
        throws KettleValueException {
    // 0 : pattern
    // 1 : Decimal separator
    // 2 : Grouping separator
    // 3 : Currency symbol

    NumberFormat nf = NumberFormat.getInstance();
    DecimalFormat df = (DecimalFormat) nf;
    DecimalFormatSymbols dfs = new DecimalFormatSymbols();

    if (!Const.isEmpty(pattern)) {
        df.applyPattern(pattern);// ww w .java 2 s .  c  om
    }
    if (!Const.isEmpty(decimal)) {
        dfs.setDecimalSeparator(decimal.charAt(0));
    }
    if (!Const.isEmpty(grouping)) {
        dfs.setGroupingSeparator(grouping.charAt(0));
    }
    if (!Const.isEmpty(currency)) {
        dfs.setCurrencySymbol(currency);
    }
    try {
        df.setDecimalFormatSymbols(dfs);
        return df.parse(value).doubleValue();
    } catch (Exception e) {
        String message = "Couldn't convert string to number " + e.toString();
        if (!isEmpty(pattern)) {
            message += " pattern=" + pattern;
        }
        if (!isEmpty(decimal)) {
            message += " decimal=" + decimal;
        }
        if (!isEmpty(grouping)) {
            message += " grouping=" + grouping.charAt(0);
        }
        if (!isEmpty(currency)) {
            message += " currency=" + currency;
        }
        throw new KettleValueException(message);
    }
}